CSS样式-清除浮动
一、为什么要清除浮动?
在某些情况下,我们不能设置父元素的高度,但是所有的子元素都是浮动的(脱标),父元素的高度为0,父元素后面的元素会上提。
二、清除浮动的四种方法:
1.额外标签法:
a.在最后增加一个额外的div,用clear: both去掉浮动属性
b.W3C推荐的一种方法
c.增加了一个莫名其妙的标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.parent {
border: 3px solid #000;
}
.child-1 {
width: 100px;
height: 100px;
background-color: #f00;
float: left;
}
.child-2 {
width: 80px;
height: 80px;
background-color: #0f0;
float: left;
}
.parent2 {
width: 250px;
height: 250px;
background-color: #00f;
}
</style>
</head>
<body>
<div class="parent">
<div class="child-1"></div>
<div class="child-2"></div>
<!-- 一般放在父元素的最后一个 -->
<div style="clear: both"></div>
</div>
<div class="parent2"></div>
</body>
</html>
或者写成:

2.overflow:hidden(在父级元素上增加overflow:hidden,不是在子级元素上增加)
强制父元素计算内部高度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.parent {
border: 3px solid #000;
overflow: hidden;
}
.child-1 {
width: 100px;
height: 100px;
background-color: #f00;
float: left;
}
.child-2 {
width: 80px;
height: 80px;
background-color: #0f0;
float: left;
}
.parent2 {
width: 250px;
height: 250px;
background-color: #00f;
}
</style>
</head>
<body>
<div class="parent">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<div class="parent2"></div>
</body>
</html>
3.after伪元素
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style type="text/css">
.parent {
border: 3px solid #000;
}
.clearfix:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
/* 兼容ie的写法 */
.clearfix {
*zoom: 1;
}
.child-1 {
width: 100px;
height: 100px;
background-color: #f00;
float: left;
}
.child-2 {
width: 80px;
height: 80px;
background-color: #0f0;
float: left;
}
.parent2 {
width: 250px;
height: 250px;
background-color: #00f;
}
</style>
</head>
<body>
<div class="parent clearfix">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<div class="parent2"></div>
</body>
</html>
4.before-after伪元素清除浮动
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style type="text/css">
.parent {
border: 3px solid #000;
}
.clearfix:after,
.clearfix:before {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
.child-1 {
width: 100px;
height: 100px;
background-color: #f00;
float: left;
}
.child-2 {
width: 80px;
height: 80px;
background-color: #0f0;
float: left;
}
.parent2 {
width: 250px;
height: 250px;
background-color: #00f;
}
</style>
</head>
<body>
<div class="parent clearfix">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<div class="parent2"></div>
</body>
</html>