1.父级手动给高度
缺点:不推荐使用。只适合高度固定的布局,要给出精确的高度,如果高度和父级div不一样时,会产生问题
.con{border:1px solid red;height:300px;}
.left{width:100px;height:100px;float:left;background: green;}
.right{width:200px;height:150px;float:left;background: blue;}
<div class="con clearfloat">
<div class="left">left</div>
<div class="right">right</div>
</div>
2.在末尾添加一个空div或者br标签
缺点:不推荐使用。如果页面浮动布局多,就要增加很多空div,让人感觉很不好
.con{border:1px solid red;}
.left{width:100px;height:100px;float:left;background: green;}
.right{width:200px;height:150px;float:left;background: blue;}
.clearfloat{clear:both;}
<div class="con clearfloat">
<div class="left">left</div>
<div class="right">right</div>
<br class="clearfloat">
/*<div class="clearfloat"></div>*/
</div>
3.父级添加overflow:hidden或者overflow:auto
缺点:不推荐使用。不能和position配合使用,因为超出的尺寸的会被隐藏。
.con{border:1px solid red;overflow:hidden;}
.left{width:100px;height:100px;float:left;background: green;}
.right{width:200px;height:150px;float:left;background: blue;}
<div class="con clearfloat">
<div class="left">left</div>
<div class="right">right</div>
</div>
4.父级添加伪元素::after和zoom
推荐使用:两句代码结合使用才能让主流浏览器都支持
.con{border:1px solid red;}
.left{width:100px;height:100px;float:left;background: green;}
.right{width:200px;height:150px;float:left;background: blue;}
.clearfloat::after{
content:",
display:block;
clear:both;
visibility:hidden,
height:0;
}
.clearfloat{
zoom:1;
}
<div class="con clearfloat">
<div class="left">left</div>
<div class="right">right</div>
</div>
网友评论