css 消除浮动方法

清除浮动

问题:当全部子类元素浮动(float)时,父级无法根据子元素的高度拉升,这时候需要我们消除浮动。

1
2
3
4
5
6
7
8
9
<style>
.box { border: 1px black solid;}
.div1 {width:100px; height: 100px; float: left; background: red;}
.div2 {width:100px; height: 100px; float: left; background: blue;}
</style>
<div class="box">
<div class="div1"></div>
<div class="div2"></div>
</div>

一、clear:both

1
2
3
4
5
6
7
8
9
10
<style>
.box { border: 1px black solid;}
.div1 {width:100px; height: 100px; float: left; background: red;}
.div2 {width:100px; height: 100px; float: left; background: blue;}
</style>
<div class="box">
<div class="div1"></div>
<div class="div2"></div>
<div style="clear:both"></div>
</div>

在浮动元素后使用一个空元素如<div class="clear"></div>,并在CSS中赋予.clear{clear:both;}属性即可清理浮动。亦可使用<br class="clear" /><hr class="clear" />来进行清理
优点:简单,代码少,浏览器兼容性好。
缺点:需要添加大量无语义的html元素,代码不够优雅,后期不容易维护。

二、overflow:hidden

1
2
3
4
5
6
7
8
9
10
11
<style>
.box { border: 1px black solid; overflow: hidden; zoom:1;/*兼容ie6*/}
.div1 {width:100px; height: 100px; float: left; background: red;}
.div2 {width:100px; height: 100px; float: left; background: blue;}
</style>

<div class="box">
<div class="div1"></div>
<div class="div2"></div>
<div></div>
</div>

给浮动元素的容器添加overflow:hidden;或overflow:auto;可以清除浮动,另外在 IE6 中还需要触发 hasLayout ,例如为父元素设置容器宽高或设置 zoom:1。
在添加overflow属性后,浮动元素又回到了容器层,把容器高度撑起,达到了清理浮动的效果。

三、在伪元素中添加clear:both;

1
2
3
4
5
6
7
8
9
10
11
<style>
.box { border: 1px black solid; zoom:1;}/* zoom 兼容ie6*/
.box:before,.box:after{content:"";display: block;} /*让伪元素成为块级元素 */
.box:after {clear:both;} /*添加清除浮动*/
.div1 {width:100px; height: 100px; float: left; background: red;}
.div2 {width:100px; height: 100px; float: left; background: blue;}
</style>
<div class="box">
<div class="div1"></div>
<div class="div2"></div>
</div>