清除浮动是前端开发初学者比较头疼的问题,下面就前辈经验和实际项目中用到的解决方法:
1.利用伪对象after方法(推荐)
定义一个样式类 clearfix,使用伪对象after,来控制浮动元素的影响。
.clearfix:after{ height:0;line-height:0; content:" "; display:block; visibility:hidden; clear:both;}
.clearfix{ zoom:1;} //ie7兼容问题
把 clearfix 加入父级元素class即可。代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>清除浮动</title>
<style type="text/css">
.clearfix:after{height:0;line-height:0; content:" "; display:block; visibility:hidden; clear:both;}
.clearfix{zoom:1;} /*ie7兼容问题*/
.container{width:400px;border:1px solid red;}
.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
</style>
</head>
<body>
<div class="container clearfix">
<div class="con_left"></div>
<div class="con_right"></div>
</div>
</body>
</html>
2.对父级CSS选择器加overflow:hidden样式(注意:如果子元素使用定位布局,无效。)
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>清除浮动</title>
<style type="text/css">
.overflow_h{overflow: hidden;}
.container{width:400px;border:1px solid red;}
.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
</style>
</head>
<body>
<div class="container overflow_h">
<div class="con_left"></div>
<div class="con_right"></div>
</div>
</body>
</html>
3.在父级“</div>”结束前,新加一个div对应选择器样式为“clear:both”
代码如下:
<span style="font-size:12px;"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>清除浮动</title>
<style type="text/css">
.clear_b{clear: both;}
.container{width:400px;border:1px solid red;}
.con_left{float: left;width: 100px;height: 100px;border:1px solid blue;}
.con_right{float: right;width: 200px;height: 200px;border:1px solid deepskyblue;}
</style>
</head>
<body>
<div class="container">
<div class="con_left"></div>
<div class="con_right"></div>
<div class="clear_b"></div>
</div>
</body>
</html></span>