在我们进行项目开发时,浮动往往是经常用到的。在给元素浮动的时候会出现一个问题,就是给某些元素添加浮动属性:float:left/right;会使得它的父元素的高度不能被撑大,也就是我们常说的高度塌陷;即height:auto会失效;解决的办法有很多。第一种就是给父元素一个固定高度,一般不这么做,第二种就是添加一个空标签,这个空标签写上:clear:both即可;第三种是比较常用也是很好用的,使用一个伪类来清除浮动;具体代码如下:

//第二种方法 测试的时候可以取消clear:both属性来观看效果更利于学习

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: auto;
background-color: skyblue;
}
.box1,.box2,.box3{
width: 400px;
height: 100px;
float: left;
background: red;
margin-bottom: 10px;
}
.footer{
width: 500px;
height: 100px;
background: blue;
}
.c{
clear: both;
}
</style>
<body>
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3">box3</div>
<div class="c"></div>
</div>
<div class="footer">footer</div>
</body>
</html>

 

 

//第三种方法  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box{padding:10px; background:gray;}
.fix{*zoom:1;}
.fix:after{display:block; content:"clear"; height:0; clear:both; overflow:hidden; visibility:hidden;}
.l{float:left;}
</style>
</head>
<body>
<div class="box fix">
<img class="l" src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" />
</div>
<p style="width: 200px;height: 100px;background: red;border-radius:200px/100px;"></p>
</body>

</html>