css 清除浮动几种方法推荐

1,父级div定义 伪类:after 和 zoom

<style type="text/css">

.div1{background:#000080;border:1px solid red;}

.div2{background:#800080;border:1px solid red;height:100px;margin-top:10px}

.left{float:left;width:20%;height:200px;background:#DDD}

.right{float:right;width:30%;height:80px;background:#DDD}

/*清除浮动代码*/

.clearfloat:after{          //IE8以上和非IE浏览器才支持:after

display:block;

clear:both;

content:"";

visibility:hidden;

height:0

}

.clearfloat{zoom:1}

</style>

<div class="div1 clearfloat">

    <div class="left">Left</div>

    <div class="right">Right</div>

</div>

<div class="div2">

div2

</div>

原理:IE8以上和非IE浏览器才支持:after,zoom(IE转有属性)可解决ie6,ie7浮动问题

优点:浏览器支持好,不容易出现怪问题(目前:大型网站都有使用,如:腾迅,网易,新浪等等)

缺点:代码多,不少初学者不理解原理,要两句代码结合使用,才能让主流浏览器都支持。

建议:推荐使用,建议定义公共类,以减少CSS代码。

 

 2.960 CSS 框架的作者的博客

html body div.clear,
html body span.clear
{
     background: none;
     border: 0;
     clear: both;
     display: block;
     float: none;
     font-size: 0;
     margin: 0;
     padding: 0;
     overflow: hidden;
     visibility: hidden;
     width: 0;
     height: 0;
}

这个样式可以通过在页面中添加<div class=”clear”></div> 或
<span class=”clear”> </span>来清除页面中的浮动。

3.

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

 

 

 

 

 

这个是优化版的清除浮动的样式,很值得推荐。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2012-11-07 16:18  hlp鹏  阅读(98)  评论(0编辑  收藏  举报