以前总是加一个<div sytle="clear:both"></div>来解决,但这样会增加无语义的标签,下面是用after伪类实现,兼容多种浏览器
.clearfix:after{
content:".";
display:block;
height:0;
clear:both;
visibility:hidden;
}
为兼容IE6,IE7,因为ie6,ie7不能用after伪类。加上下面代码
.clearfix{zoom:1}
一般情况下,如果父层内部有浮动(float)可能导致父层的高度为0,加上clearfix后就行了:
<style type="text/css">
.clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden;}
.clearfix{zoom:1}
.parent{width:120px;}
.left{float:left;display:inline;}
.right{float:right;display:inline;}
</style>
<div class="clearfix">
<div class="left">
left
</div>
<div class="right">
right
</div>
</div>