清除浮动bug使用 .clearfix{*zoom:1;} 和 .clearfix:after

1:  .clearfix{*zoom:1;} /*这是针对于IE6/7的,因为IE6/7不支持:after伪类,这个神奇的zoom:1让IE6/7的元素可以清除浮动来包裹内部元素。具体意思的话,不用深究,听说微软的工程师自己都无法解释清楚。height:1%效果也是一样*/
2:  .clearfix:after{display:block; overflow:hidden; clear:both; height:0; visibility:hidden; content:".";}
3:   

作用:可以在子节点float的时候撑开父节点.整段代码就相当于在浮动元素后面跟了个宽高为0的空div然后设定它clear:both来达到清除浮动的效果。 之所以用它是因为你不必在html文件中写入大量无意义的空标签又能清除浮动。

使用方法,只要写一个.clearfix就行了然后在需要清浮动的元素中 添加clearfix类名就好了。 如

<div class="head clearfix"></div>

 

我们以前清除浮动的时候,都是在div的结尾,加多一个无用的  <div class="clear"></div>

例如:

在写HTML代码的时候,发现在Firefox等符合W3C标准的浏览器中,如果有一个DIV作为外部容器,内部的DIV如果设置了float样式,则外部的容器DIV因为内部没有clear,导致不能被撑开。看下面的例子:
<div style="border:2px solid red;">
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">CSSBBS</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
</div>
运行这段代码,大家可以看到,作为外部容器的边框为红色的DIV,没有被撑开。这是因为内部的DIV因为float:left之后,就丢失了clear:both和display:block的样式,所以外部的DIV不会被撑开。
我们想让外部容器的DIV随着内部DIV增多而增加高度,要怎么解决呢?
以前我都是用这样的方法来解决:
<div style="border:2px solid red;">
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="float:left;width:80px;height:80px;border:1px solid blue;">TEST DIV</div>
<div style="clear:both;"></div>
</div>
我们看到,在容器DIV内要显示出来的float:left的所有的DIV之后,我们添加了这样的一个DIV:<div style="clear:both"></div> 。这样,其实就在最后增加了clear的动作。

转载于:https://www.cnblogs.com/joeylee/archive/2013/04/18/3029063.html

THE END
< <上一篇
下一篇>>