闭合浮动

方法一:

.clearfix:after {content:"."; display:block; height:0; clear:both; } 
.clearfix { *zoom:1; }

1) display:block 使生成的元素以块级元素显示,占满剩余空间; 
2) height:0 避免生成内容破坏原有布局的高度。 
3) visibility:hidden 使生成的内容不可见,并允许可能被生成内容盖住的内容可以进行点击和交互; 
4)通过 content:"."生成内容作为最后一个元素,至于content里面是点还是其他都是可以的,例如oocss里面就有经典的 content:"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",有些版本可能content 里面内容为空,一丝冰凉是不推荐这样做的,firefox直到7.0 content:”" 仍然会产生额外的空隙; 
5)zoom:1 触发IE hasLayout。 
通过分析发现,除了clear:both用来清除浮动的,其他代码无非都是为了隐藏掉content生成的内容,这也就是其他版本的闭合浮动为什么会有font-size:0,line-height:0。 

方法二:

.clearfix:before,.clearfix:after { 
    content:""; 
    display:table; 

.clearfix:after { clear:both; }/* For IE 6/7 (trigger hasLayout) */ 
.clearfix { zoom:1; } 

Block formatting contexts (块级格式化上下文),以下简称 BFC。 

那么如何触发BFC呢? 
float 除了none以外的值 
overflow 除了visible 以外的值(hidden,auto,scroll ) 
display (table-cell,table-caption,inline-block) 
position(absolute,fixed)

触发hasLayout的条件: 
position: absolute 
float: left|right 
display: inline-block 
除 “auto” 外的任意值 
height: 除 “auto” 外的任意值 (例如很多人清除浮动会用到 height: 1% ) 
zoom: 除 “normal” 外的任意值

在支持BFC的浏览器(IE8+,firefox,chrome,safari)通过创建新的BFC闭合浮动; 
在不支持 BFC的浏览器 (IE6-7),通过触发 hasLayout 闭合浮动。 

网址:http://www.jb51.net/css/67471.html