第一种方式,使用空标签来设置 clear:both,用于清除浮动。
但是添加一个并没有实质内容的标签并不符合简化页面结构的目的,而且在 JavaScript 操作子元素时很容易引起 bug。
Code
<style media="all">
.children {float:left;}
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
}
</style>
<div class="parent ">
<div class="children">子元素</div>
<div class="children">子元素</div>
<div class="children">子元素</div>
<div class="clear"></div>
</div>
<div class="children">又一行</div>
第二种方式,利用:after 伪类
Code
<style media="all">
.children {float:left;}
.clear {
clear: both;
display: block;
overflow: hidden;
visibility: hidden;
}
.clearfix:before,
.clearfix:after {
content: '.';
display: block;
overflow: hidden;
visibility: hidden;
font-size: 0;
line-height: 0;
0;
height: 0;
}
.clearfix:after {
clear: both;
}
/*
The following zoom:1 rule is specifically for IE6 + IE7.
Move to separate stylesheet if invalid CSS is a problem.
*/
.clearfix{
zoom: 1;
}
</style>
<div class="parent clearfix">
<div class="children">子元素</div>
<div class="children">子元素</div>
<div class="children">子元素</div>
</div>
<div class="children">又一行</div>
<div class="clear"></div>
<div class="parent ">
<div class="children">子元素</div>
<div class="children">子元素</div>
<div class="children">子元素</div>
<div class="clear"></div>
</div>
<div class="children">又一行</div>
几点说明:
1,:after 伪元素在元素之后添加内容。默认地,这个伪元素是行内元素,不过可以使用属性 display 改变这一点。同理:before
2,IE6浏览器会执行zoom:1表示对象的缩放比例,但这里 overflow:hidden;和_zoom:1;是连起来用的,作用是清除clearfix内部浮动。 同理,还可以使用同样方法清除margin属性在IE浏览器中的重叠问题。具体参考CSS Hack 汇总快查
3,整理自960-Grid-System
参考阅读:http://www.woyaya.net/about-css-clear-floating.html