(一)为什么要清除浮动?
添加浮动之前:
- 给father元素添加border
- 在father这个父元素内部添加两个子元素(son1和son2)(注意:这里son1和son2并没有设置浮动)
- 在father元素下面添加一个footer元素。
可以得到以下显示结果:
添加浮动之后:
结果发现:
father元素变成了一条线,footer元素上移。这也就是我们所说的高度塌陷。
高度塌陷:当所有的子元素浮动的时候,且父元素没有设置高度,这时父元素就会产生高度塌陷。
所以, 我们就需要清除浮动,避免高度塌陷的情况发生。
基本结构的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.son1{
width: 400px;
height: 400px;
background: darkorange;
float: left;
}
.son2{
width: 200px;
height: 200px;
background: pink;
float: left;
}
.father{
border: solid 1px;
}
.footer{
width: 1000px;
height: 300px;
background: cornflowerblue;
}
</style>
</head>
<body>
<div class="father">
<div class="son1">son1</div>
<div class="son2">son2</div>
</div>
<div class="footer">footer</div>
</body>
</html>
(二)清除浮动的几种方式
(1)给父元素定义overflow: hidden;(不推荐!)
不推荐! 溢出元素框的部分会被隐藏。布局时需要注意。
清除浮动后的显示:
(2)在浮动元素后面添加一个空标签,并定义clear: both;(不推荐!)
不推荐! 增加了一个空标签,语义化差,不利于页面优化。
clear: both;
的意义:闭合浮动,不让子元素溢出元素框。
<style>
.clear{
clear: both;
}
</style>
<body>
<div class="father">
<div class="son1">son1</div>
<div class="son2">son2</div>
<div class="clear">我是一个空标签</div>
</div>
<div class="footer">footer</div>
</body>
清除浮动后的显示:(当然,实际使用时,空标签内不添加任何内容,我加了文字方便大家理解空标签的位置)
(3)使用after伪元素清除浮动(推荐!)
推荐使用! 符合闭合浮动思想,结构语义化正确。
但是,IE6不支持伪元素:after
,需要设置zoom: 1;
触发hasLayout
。
<style>
.father{
border: solid 1px;
*zoom: 1;
}
.father:after{
content: "";
clear: both;
display: block;
height: 0;
}
</style>
<body>
<div class="father">
<div class="son1">son1</div>
<div class="son2">son2</div>
</div>
<div class="footer">footer</div>
</body>
清除浮动后的显示:
版权声明:本文为weixin_45017439原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。