CSS清除浮动的方法

1.添加空<div>标签或者<br />
[html]
<style type=”text/css”>
*{margin:0;padding:0;}
body{font:36px bold; color:#FFF; text-align:center;}
.wrap{background:#CCC;}
.left{float:left;width:40%;height:200px;background:#08F;}
.right{float:right;width:40%;height:200px;background:#F08;}
.clr{clear:both;}
</style>

<div class=”wrap”>
<div class=”left”>Left</div>
<div class=”right”>Right</div>
<div class=”clr”></div>
</div>
[/html]
:<br style=”clear:both;” />在IE6下无效。

2.使用overflow属性:设置父元素{overflow:auto;zoom:1;},{zoom:1;}用于兼容IE6。
[html]
<style type=”text/css”>
*{margin:0;padding:0;}
body{font:36px bold; color:#FFF; text-align:center;}
.wrap{background:#CCC;overflow:auto;zoom:1;}
.left{float:left;width:40%;height:200px;background:#08F;}
.right{float:right;width:40%;height:200px;background:#F08;}
</style>

<div class=”wrap”>
<div class=”left”>Left</div>
<div class=”right”>Right</div>
</div>
[/html]
:在IE5/Mac上使用这种方法,必须设定overflow为hidden。

3.设置父元素一起浮动
[html]
<style type=”text/css”>
*{margin:0;padding:0;}
body{font:36px bold; color:#FFF; text-align:center;}
.wrap{background:#CCC;float:left;}
.left{float:left;width:40%;height:200px;background:#08F;}
.right{float:right;width:40%;height:200px;background:#F08;}
</style>

<div class=”wrap”>
<div class=”left”>Left</div>
<div class=”right”>Right</div>
</div>
[/html]
注:父元素一起浮动在标准浏览器里面要设置父元素的宽度。

4.设置父元素固定高度
[html]
<style type=”text/css”>
*{margin:0;padding:0;}
body{font:36px bold; color:#FFF; text-align:center;}
.wrap{background:#CCC;height:200px;}
.left{float:left;width:40%;height:200px;background:#08F;}
.right{float:right;width:40%;height:200px;background:#F08;}
</style>

<div class=”wrap”>
<div class=”left”>Left</div>
<div class=”right”>Right</div>
</div>
[/html]

5.定义父元素display:table
[html]
<style type=”text/css”>
*{margin:0;padding:0;}
body{font:36px bold; color:#FFF; text-align:center;}
.wrap{background:#CCC;display:table;}
.left{float:left;width:40%;height:200px;background:#08F;}
.right{float:right;width:40%;height:200px;background:#F08;}
</style>

<div class=”wrap”>
<div class=”left”>Left</div>
<div class=”right”>Right</div>
</div>
[/html]
:不适用IE6

方法比较:

1.添加额外标签,是W3C推荐的做法,但是会增加不必要的代码。
2.使用overflow的时候,可能会对页面表现带来影响,最好在多个浏览器上测试;
3.父元素一起浮动,要注意对前后相邻元素的影响。
4.设置父元素高度,不能清除浮动,但是能解决浮动带来的一些问题,新的问题是父元素不能自动变化高度。
5.设置父元素display:table,IE6无效,而且可能带来新的问题。

您的赞助将会支持作者创作及本站运维

发表评论


TOP