首页 > 技术文章 > 清除浮动的方法

zhuifeng 2014-07-21 10:30 原文

为什么要清除浮动?

当元素使用了float样式而没有清除浮动的时候,有浮动元素的父元素容器将无法自动撑开。也就是说当一个元素是浮动的,如果没有关闭浮动,其父元素不会包含这个浮动元素,因为浮动元素从文档流中脱离,从而会影响到前后标签、父级标签的位置及 width height 属性。

 

通过设置父元素属性overflow:hidden来达到清除浮动的目的

<!--zoom: 1用于在IE下触发其layout-->
<div  style="background:#00f; overflow:hidden; zoom:1;">
    <div style="float:left; width:20px; height:20px; background:#d00;"></div>
    <div style="float:left; width:20px; height:20px; background:#d00;"></div>
</div>

 

通过设置父元素伪类:after和zoom来达到清除浮动的目的

/*清除浮动代码*/
.clearfloat:after{display:block;clear:both;content:"";visibility:hidden;height:0}
.clearfloat{zoom:1}
<div class="clearfloat"> 
    <div style="float:left; width: 20px; height: 20px; background: #00d;">Left</div> 
    <div style="float:left; width: 20px; height: 20px; background: #00d;">Left</div> 
</div>
 

推荐阅读