清除浮动

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.container{width:300px; border:1px solid #000;}
.f1{width: 50px;height:50px;background: gold;float: left;}
.f2{width: 50px;height:50px;background: blueviolet;float: left;}
</style>
</head>
<body>
<div class="container">
<div class="f1"></div>
<div class="f2"></div>
</div>
<div>浮动之后的元素</div>
</body>
</html>
运行效果如下:

原因:container容器没有设置高度,由于container容器中的元素浮动,导致容器的高度为零
解决办法1:给容器设置高度 .container{height:60px}
解决办法2:给容器设置overflow属性 .container{overflow:hidden;}
解决办法3:给容器增加没有意义的空元素,设置其属性clear:both;
<div class="container">
<div class="f1"></div>
<div class="f2"></div>
<div style="clear: both"></div>
</div>
<div>浮动之后的元素</div>
解决办法4:利用css内容生成空元素,并且设置其display:block;(空元素必须是块级元素),clear:both;属性

.container:after{
content: "";
display: block;
clear: both;
}
第四种方案最好,最实用!!!
 
 
    
 
 

 
posted @ 2017-08-09 11:07  Ai-Long  阅读(153)  评论(0编辑  收藏  举报