CSS 浮动基本概念

浮动在文档布局中是一个非常重要的概念,CSS 允许浮动任何元素。

浮动属性 float

定义
指定元素在哪个方向上浮动。
属性值
  • left - 元素向左浮动

  • right - 元素向右浮动

  • none - 元素不浮动,并且会显示在其在文本中出现的位置

  • inherit - 从父元素继承属性值

浮动的特性

1. 浮动元素会被从正常文档流中删除,不过还是会影响文档的布局

css:

.float_right {

    float: right;

}

html:    

<p>

    When the farmer was old, and felt that his time had come to die, he called the three sons to him and said, <img src="./images/gold.jpg" class="float_right" /> "My sons, there is a pot of gold hidden in the olive orchard. Dig for it, if you wish it."

</p>

如代码所示,文本中插入了一个向右浮动的图片,运行效果如下:


可以看出图片出现的位置不是其在文本中声明的位置。不过也是由于图片的浮动,所以其他文本的位置出现了变化。之所以会出现这样的效果,是因为当一个元素浮动时,其他内容会环绕该元素。

2. 浮动元素周围的外边距不会被合并

css:

img {

    margin20px;

    width300px;

    height200px;

}


.float_left {

    float: left;

    border1px solid yellow;

}


.control-text {

    margin20px;

    border1px solid blue;

}

html:

<p class="control-text">

    They dug until they had turned up the soil from one end of the orchard to the other, round the tree-roots and between them. But no pot of gold was to be found. It    seemed as if someone must have stolen it, or as if the farmer had been wandering in his wits. The three sons were bitterly disappointed to have all their work for nothing.

</p>

<img src="./images/labor.jpg" class="float_left" />

<p class="control-text">

    The next olive season, the olive trees in the orchard bore more fruit than they

    had ever given; when it was sold, it gave the sons a whole pot of gold.

</p>

代码中为文本元素和图片同时添加了外边距,运行效果如下:


如图,两个文本片段设置了 margin,它们之间的 margin 被合并为了一个。而由于图片设置了 float 属性,文本和图片之间的 margin 是各自独立的。

3. 距离浮动元素最近的块级祖先元素是它的包含块

4. 浮动元素会生成一个块级框,不管它本身是什么


更多 CSS 技巧,请关注微信公众号