****导致父容器高度塌陷的主要原因就是子容器使用float会使元素脱离文档流****
例如:下图中的三个div本来是在红色边框中,但是因为这三个div使用了float:left;导致了红色边框的父容器高度塌陷,也就没有了高度,从而显示成了一条红线。

****解决方法一****
为父元素添加overflow:hidden;

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box{border: 1px red solid;overflow: hidden;}
.one{height: 30px;width: 100px;background-color: #666;float: left;}
.two{height: 30px;width: 100px;background-color: #999000;float: left;}
</style>
</head>
<body>
<div class="box">
<div class="one">First</div>
<div class="two">Second</div>
</div>
</body>
</html>
****解决方法二****
在父元素</div>前添加一个<div class="clear"></div>并且为这个div添加属性clear:both;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box{border: 1px red solid;}
.one{height: 30px;width: 100px;background-color: #666;float: left;}
.two{height: 30px;width: 100px;background-color: #999000;float: left;}
.clear{clear: both;}
</style>
</head>
<body>
<div class="box">
<div class="one">First</div>
<div class="two">Second</div>
<div class="clear"></div>
</div>
</body>
</html>
****解决方法三****
因为导致父元素高度塌陷的原因就是子元素脱离文档流,这样我们就给父元素添加一个高度属性就可以了,前提这个方法需要知道子元素的高度才能适当的给父元素添加所需要的高度
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box{border: 1px red solid;height: 30px;}
.one{height: 30px;width: 100px;background-color: #666;float: left;}
.two{height: 30px;width: 100px;background-color: #999000;float: left;}
</style>
</head>
<body>
<div class="box">
<div class="one">First</div>
<div class="two">Second</div>
</div>
</body>
</html>
网友评论