代码改变世界

css清除浮动各方法

2012-03-09 14:47  VVG  阅读(344)  评论(0编辑  收藏  举报
 (1)空标签法:
       这种方法应该说是最简单的一种了,W3C建议在容器的末尾增加一个“clear:both"的元素,强迫容器适应它的高度以便装下所有的float,并没限制使用什么样的标签,有用<br style=”clear:both”/>的,有用空<div style=”clear:both”></div>的;比如:  
 
<div> <div style ="float:left; width:40%;"> <p> Some content </p></div> <p> Text outside the float </p> <div style ="clear:both;" ></div> </div>


(2)父元素使用overflow的方法:

       通过设置父元素overflow值设置为hidden或者auto;不过,在<=IE6中使用这个方法,还需要haslayout,还有,使用overflow=hidden的时候,一旦你有定位需求可能会因此而难以实现,使用这种方法前你应该至少确定:
       a.父元素的height是自适应的;

       b.浮动元素的宽度不大于父元素的宽度,即没有溢出需求;所以,这种方法也有它的局限性; 

<div style ="overflow:hidden; width:100%;"> <div style ="float:left;width:30%;" > <p>the widths of the combined floats never exceed the width of the container</p> </div> </div>


(3)
伪类:after

       这种方法应该说是目前应用最广泛的方法,它的优势:没有多余的标记添加到容器中;通过使用:after产生的content不能接受某些属性,包括'position','float',列表属性,表格属性,但是clear属性可以被接受。
       不过,不幸的是,IE不支持:after方法,但又幸运的是,回顾前面,如果IE在父容器拥有Width/Height等layout状态下,会完成自动闭合,称之为“auto-clearing”;那么,对于IE/win,我们使用设定zoom:1的方法的方法来实现和:after一样的效果.于是一个类似这样的样式出现了:
.clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden;}
.clearfix
{zoom:1;}
<div class="clearfix"><div style ="float:left;width:30%;" ><p>take :after</p></div> </div>