目录
前言
float+margin布局是常用的布局方法之一,但是float布局有可能引起高度坍塌,该怎么解决呢
问题
可以看到红色框框跑上面去了,这是因为采用float后的元素是脱离了文档流的,不影响其他元素的布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.div1 {
width: 400px;
background-color: green;
}
.div3 {
float: left;
width: 200px;
height: 50px;
background-color: yellow;
}
.div2 {
width: 400px;
height: 300px;
background-color: red;
}
</style>
</head>
<body>
<div class="div1">
<span>哎呀~高度坍塌了</span>
<div class="div3"></div>
<div class="div3"></div>
</div>
<div class="div2"></div>
</body>
</html>
解决方法
让采用float布局的元素的盒子管理自己的布局
方法一
.div1 {
width: 400px;
background-color: green;
overflow: hidden; /*或者overflow:hidden*/
}
方法二
.div1::after {
content: '';
clear: both; /*这个的意思是左右两边都没有float布局的元素*/
display: block;
height: 0;
}