css:清除浮动的三种方式及其原理

清除浮动的三种方式及其原理
浮动元素的特性
浮动元素脱离文档流,不占据空间。浮动元素碰到包含它的边框或者浮动元素的边框停留。

浮动元素带来的问题
因为浮动元素脱离文档流,所以对于其处于正常文档流中父元素,无法获知其高度,导致父元素自身的高度塌陷(失去浮动元素占据的高度)。

清除浮动的三种方式
设置float

overflow:hidden;
<div style="overflow:hidden;zoom:1;">
    <p style="float: left;">使用overflow:hidden 清除浮动</p>
</div>
 


 
其中,zoom:1;用于兼容IE6。

clear:both;
<style>
.clearfix:after{
    /*START 真正起到清除浮动的代码*/
    content: '';
    display: block;
    clear: both;
    /*END 真正起到清除浮动的代码*/
    height:0;
}
.clearfix{display: inline-block;} /* for IE/Mac */
</style>
<div class="clearfix">
    <div style="float: left;">clear:both ;son div</div>
</div>
 
清除浮动本质上是说要清除浮动元素带来的一些影响(例如高度塌陷)。在上面的例子中,我们给 :after伪元素添加了clear:both;属性,为了解释这个属性的作用,我们看下面的一段代码。

<div style="width: 150px; border: 1px solid #ccc;">
    <div style="width: 100px; background: greenyellow;">div1</div>
    <div style="width: 100px; background: blueviolet; float:left;">div2</div>
    <div style="width: 120px; background: grey; clear:left;"></div>
</div>

<div style="width: 150px; border: 1px solid #ccc; margin-top: 20px;">
    <div style="width: 100px; background: greenyellow;">div1</div>
    <div style="width: 100px; background: blueviolet; float:left;">div2</div>
    <div style="width: 120px; background: grey;  "></div>
</div>
 

clear:left;会让元素跟在其左侧浮动元素的后面,而不会忽略前面的浮动元素,位于浮动元素后面。 同理,clear:right;则会清除元素右侧浮动元素的影响。 而clear:both;就是清除左右两侧的影响。

另外一种方式position:absolute;
不推荐这种方式,因为这需要改变父元素本身的position属性。也许在某种情况下,你可以修改。但是,如果你不能修改怎么办??

<div style="position:absolute;">
    <div style="float: left;">postion:absolute clear float</div>
</div>
 
之所以会提到这个方式,是为了说明 前面两种方式(设置float和overflow:hidden;)清除浮动的原理:当给父元素设置overflow:hidden属性时,实际上父元素本身形成了一个BFC(Block Formating Context)。

独立的块级上下文可以包裹浮动流,全部浮动子元素也不会引起容器高度塌陷,就是说包含块会把浮动元素的高度也计算在内,所以就不用清除浮动来撑起包含块的高度。

形成一个BFC的情况:

根元素
float属性不为none
position为absolute或fixed
display为inline-block, table-cell, table-caption, flex, inline-flex
overflow不为visible
————————————————
 

猜你喜欢

转载自blog.csdn.net/zhang8593/article/details/129901462