[CSS]清除浮动的三个方法

来源:互联网 发布:推倒女神的体验知乎 编辑:程序博客网 时间:2024/05/17 20:11

一个没有设置高度的容器div内如果存在浮动元素(即使用了属性float:left或者float:right),那么该父级元素会无法展开。

举个例子,有一个div容器,div容器里有两个小容器,分别向左和向右浮动,为了区别这三个容器,分别设置了不同颜色的边框。

<html><head><style>.content {width:500px;border:1px solid red;}.left {width:100px;height:100px;border:1px dashed blue;float:left;}.right {width:100px;height:100px;border:1px dashed green;float:right;}</style></head><body><div class="content"><div class="left"></div><div class="right"></div></div></body></html>

产生效果:


注意到父级元素content没有展开。


为了使父级元素展开,有三种方法:


第一:设置父级元素的高度,但是要事先知道内容的高度,这里内部的元素高度是100像素,加上上下边框高度2像素,一共是102像素。

<html><head><style>.content {width:500px;border:1px solid red;height:102px;}.left {width:100px;height:100px;border:1px dashed blue;float:left;}.right {width:100px;height:100px;border:1px dashed green;float:right;}</style></head><body><div class="content"><div class="left"></div><div class="right"></div></div></body></html>



第二:添加样式,并在父级元素结束标签前添加both:clear样式。

<html><head><style>.content {width:500px;border:1px solid red;}.left {width:100px;height:100px;border:1px dashed blue;float:left;}.right {width:100px;height:100px;border:1px dashed green;float:right;}.clear {clear:both;}</style></head><body><div class="content"><div class="left"></div><div class="right"></div><div class="clear"></div></div></body></html>

第三:添加overflow属性:

<html><head><style>.content {width:500px;border:1px solid red;overflow:hidden;}.left {width:100px;height:100px;border:1px dashed blue;float:left;}.right {width:100px;height:100px;border:1px dashed green;float:right;}</style></head><body><div class="content"><div class="left"></div><div class="right"></div></div></body></html>