本文主要内容
本文主要介绍css浮动带来的影响以及清除浮动的几种方法
做横向布局时我们一般会写如下的代码进行布局
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<style>
.box1{background-color: pink;}
.smallbox{width: px;height:px;margin-right: px;float: left;background-color: red;}
.box2{width: px;height:px;background-color: blue;}
</style>
</head>
<body>
<div class="box1">
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
</div>
<div class="box2"></div>
</body>
</html>
运行结果如图:![]()
清除浮动的几种方法本文主要内容 此时图中所示就是浮动会带来的问题:浮动会让div元素脱离文档标准流,漂浮在标准流之上,就像图中的四个红色的box,它们浮动脱离了文档标准流,导致它们外层的box1内部相当于就没有内容了,所以它的高度就没有了,这样box2发现它上面没有东西,就跑到上面待着了.
怎么让蓝色盒子下来呢?
方法一:使用clear:both
写一个.clearfloat{clear:both;}的样式,然后将box2添加上clearfloat类
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<style>
.box1{background-color: pink;}
.smallbox{width: px;height:px;margin-right: px;float: left;background-color: red;}
.box2{width: px;height:px;background-color: blue;}
.clearfloat{clear:both;}
</style>
</head>
<body>
<div class="box1">
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
</div>
<div class="box2 clearfloat"></div>
</body>
</html>
运行结果图:这样做所有浏览器都能够达到上图的效果,但是我们现在程序存在一个问题:虽然box2盒子回到了box1的下面,但是我们并没有看到粉色的box1盒子,此时我们使用开发者工具能够很清楚的看到box1的高度是0.![]()
清除浮动的几种方法本文主要内容
方法二:使用伪类
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<style>
.box1{background-color: pink;}
.smallbox{width: px;height:px;margin-right: px;float: left;background-color: red;}
.box2{width: px;height:px;background-color: blue;}
.clearfloat:after{display: block;content: "";clear: both;height: ;visibility:hidden;}
.clearfloat{zoom:;}/*兼容IE6 7*/
</style>
</head>
<body>
<div class="box1 clearfloat">
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
</div>
<div class="box2"></div>
</body>
</html>
效果图![]()
清除浮动的几种方法本文主要内容
方法三:使用overflow
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<style>
.box1{background-color: pink;overflow:hidden/*hidden|auto都可以*/;zoom:;}
.smallbox{width: px;height:px;margin-right: px;float: left;background-color: red;}
.box2{width: px;height:px;background-color: blue;}
</style>
</head>
<body>
<div class="box1">
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
<div class="smallbox"></div>
</div>
<div class="box2"></div>
</body>
</html>
也能够达到上图的效果,我个人更推荐这种方式。
zoom:1
朋友们会发现方法二和三都出现了zoom:1,那么zoom是什么呢?
度娘告诉我们:zoom是 设置或检索对象的缩放比例。设置或更改一个已被呈递的对象的此属性值将导致环绕对象的内容重新流动。当设置了zoom的值之后,所设置的元素就会就会扩大或者缩小,高度宽度就会重新计算了,这里一旦改变zoom值时其实也会发生重新渲染,运用这个原理,也就解决了ie下子元素浮动时候父元素不随着自动扩大的问题。