CSS清除浮动
页面布局经常会使用float让元素浮动起来,可是使用了浮动属性后,会导致父级对象盒子不能被撑开,产生一些副作用,例如背景不能显示。所以清除浮动也算是一项必会技能了吧。
<style type="text/css">
.fu{background:#fff;width:100px;border:1px solid red;}
.left{float:left;width:20%;height:50px;background:#DDD}
.right{float:right;width:30%;height:30px;background:#DDD}
</style>
<div class="fu">
<div class="left">1</div>
<div class="right">2</div>
</div>

可以看到父级元素没有包裹其内容。
具有可行性的清除浮动的方法有:
1.为父级元素设置height
这种方法只适合高度固定的布局。
<style type="text/css">
.fu{background:#fff;width:100px;border:1px solid red;height:50px;}
.left{float:left;width:20%;height:50px;background:#DDD}
.right{float:right;width:30%;height:30px;background:#DDD}
</style>
<div class="fu">
<div class="left">1</div>
<div class="right">2</div>
</div>

2.使用clear:both
在父级“</div>”结束前使用一个空元素如<div class="clear"></div>,并在CSS中赋予.clear{clear:both;}属性可清理浮动。
这种方法虽然简单,但页面浮动布局多,就要增加很多空div,代码维护起来更困难,不推荐多用。
<style type="text/css">
.fu{background:#fff;width:100px;border:1px solid red;}
.left{float:left;width:20%;height:50px;background:#DDD}
.right{float:right;width:30%;height:30px;background:#DDD}
.clear{clear:both;}
</style>
<div class="fu">
<div class="left">1</div>
<div class="right">2</div>
<div class="clear"></div>
</div>
3.使用CSS的overflow属性
给浮动元素的容器添加overflow:hidden;或overflow:auto;可以清除浮动,另外在 IE6 中还需要触发 hasLayout。
<style type="text/css">
.fu{background:#fff;width:100px;border:1px solid red;overflow:hidden;*zoom: 1;}
.left{float:left;width:20%;height:50px;background:#DDD}
.right{float:right;width:30%;height:30px;background:#DDD}
</style>
<div class="fu">
<div class="left">1</div>
<div class="right">2</div>
</div>
4.父级div定义伪类:after 和 zoom
原理是在元素末尾添加一个看不见的块元素来清除浮动,可以完美兼容当前主流的各大浏览器。使用时建议定义公共类,来减少CSS代码。
<style type="text/css">
.fu{background:#fff;width:100px;border:1px solid red;}
.left{float:left;width:20%;height:50px;background:#DDD}
.right{float:right;width:30%;height:30px;background:#DDD}
/*清除浮动代码*/
.clearfloat:after{content:"020";display:block;clear:both;visibility:hidden;height:0}
.clearfloat{zoom:1}
</style>
<div class="fuclearfloat">
<div class="left">1</div>
<div class="right">2</div>
</div>
注:"zoom:1"是为了触发IE6的haslayout。

浙公网安备 33010602011771号