1.結尾處添加空div標籤設置clear:both
在浮動的盒子之下再放一個標籤,在這個標籤中使用clear:both,用來清除浮動,這種清除浮動的方式會增加頁面的標籤,如果頁面浮動佈局多,就會有很多空的div,會導致造成頁面結構混亂。例子如下:
<style type="text/css">
.div{
background:red;
width:200px
}
.left{
float:left;
width:50px;
height:100px;
background:green
}
.right{
float:right;
width:100px;
height:50px;
background:blue
}
/*清除浮動*/
.clear{
clear:both
}
</style>
<div class="div">
<div class="left"></div>
<div class="right"></div>
<div class="clear"></div>
</div>
2.父級使用overflow:hidden來清除浮動
在浮動元素的父元素中添加一個屬性:overflow:hidden,就可以清除這個父元素中的子元素的浮動.需要注意的是:overflow:hidden會將超出的部分隱藏,所以這種方法不可以與position配合使用。例子如下:
<style type="text/css">
.div{background:#000080;border:1px solid red;width:200px;overflow:hidden}
.left{float:left;width:20%;height:200px;background:green}
.right{float:right;width:30%;height:50px;background:blue}
</style>
<div class="div">
<div class="left"></div>
<div class="right"></div>
</div>
3.父級定義僞類after和zoom
after支持IE8以上瀏覽器和非IE瀏覽器,zoom可解決IE6,IE7浮動問題,這種方法瀏覽器支持性好,不容易出現兼容問題,可以定義成公共類,以減少css代碼。例子如下:
<style type="text/css">
.div{background:red,width:200px}
.left{float:left;width:30%;height:200px;background:green}
.right{float:right;width:50%;height:100px;background:blue}
/*清除浮動*/
.clear:after{display:block;clear:both;content:"";visibility:hidden;height:0}
.clear{zoom:1}//兼容IE
</style>
<div class="div clear">
<div class="left"></div>
<div class="right"></div>
</div>