为什么要清除浮动?
下面的例子是浮动对元素的影响
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<style type="text/css">
.box1 {
width: 100px;
background: #999;
}
.box2 {
width: 100px;
height: 40px;
}
.box3 {
width: 100px;
height: 40px;
background-color: #333;
}
</style></head><body>
<p class="box1">
<p class="box2"></p>
</p>
<p class="box3"></p></body></html>
box2加入float: left属性后的结果如下
如图所示,由于box1未设置高度,box3自动补位,如果这样的话,页面就会混乱。所以,我们需要清除这种浮动
以下是清除浮动的几种方法
(1)clear: both
通过给浮动元素下添加p标签并设置clear: both属性
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<style type="text/css">
.box1 {
width: 100px;
background: #999;
}
.clear {
clear: both;
}
.box2 {
width: 100px;
height: 40px;
float: left;
}
.box3 {
width: 100px;
height: 40px;
background-color: #333;
}
</style></head><body>
<p class="box1">
<p class="box2"></p>
<p class="clear"></p>
</p>
<p class="box3"></p></body></html>
优点:简单、代码少、浏览器支持好
缺点:增加了无意义的标签
(2)overflow: hidden
通过给浮动元素的父元素添加overflow: hidden属性来清除浮动
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<style type="text/css">
.box1 {
width: 100px;
background: #999;
}
.clear {
overflow: hidden;
zoom: 1; /*处理兼容性问题*/
}
.box2 {
width: 100px;
height: 40px;
float: left;
}
.box3 {
width: 100px;
height: 40px;
background-color: #333;
}
</style></head><body>
<p class="box1 clear">
<p class="box2"></p>
</p>
<p class="box3"></p></body></html>
优点: 简单、代码少、浏览器支持好
缺点:超出的内容会被隐藏
(3)加入after伪类
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<style type="text/css">
.box1 {
width: 100px;
background: #999;
}
.clear:after {
clear: both;
content: "";
display: block;
visibility: hidden;
}
.box2 {
width: 100px;
height: 40px;
float: left;
}
.box3 {
width: 100px;
height: 40px;
background-color: #333;
}
</style></head><body>
<p class="box1 clear">
<p class="box2"></p>
</p>
<p class="box3"></p></body></html>
优点:浏览器支持好
缺点:代码多
第三种方法是现在许多浏览器所用的方法,所以清除浮动时最好用after伪类
以上就是清除浮动有哪些方法及优缺点 的详细内容。