一:我们在使用浮动时,不可避免的会遇到高度塌陷的问题。
因为常规流盒子在计算高度时,不考虑浮动盒子。
举例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.box{
width: 100px;
height: 100px;
}
.one{
background-color: red;
}
.two{
background-color: blue;
}
.three{
background-color: green;
}
.four{
background-color: yellow;
}
/* 浮动 */
.fl{
float: left;
}
</style>
</head>
<body>
<div class="content clearfix">
<div class="box one fl"></div>
<div class="box two fl"></div>
<div class="box three fl"></div>
<div class="box four fl"></div>
</div>
<p>hello world!</p>
</body>
</html>
效果图为
按照常规流来看,hello world应该在盒子的下方,但是现在却跟着盒子后面。影响了我们原本的目的(让盒子横向排列,不包括其它元素)。所以我们要清除浮动带来的影响。
二:清除浮动办法。
- clear:left/right/both;
- 父元素设置overflow的值为visible;
- 给父元素添加一个伪类。
建议使用使用第三种方法:主要问题是有的浏览器不支持(IE)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.box{
width: 100px;
height: 100px;
}
.one{
background-color: red;
}
.two{
background-color: blue;
}
.three{
background-color: green;
}
.four{
background-color: yellow;
}
/* 浮动 */
.fl{
float: left;
}
/* 清除浮动 */
.clearfix::after{
content: " ";
display: block;
clear: both;
}
</style>
</head>
<body>
<div class="content clearfix">
<div class="box one fl"></div>
<div class="box two fl"></div>
<div class="box three fl"></div>
<div class="box four fl"></div>
</div>
<p>hello world!</p>
</body>
</html>
效果: