为什么要清除浮动,这就不需要简述了吧,我们直接进入正题。

首先看看未清除浮动时的样子:

再来看一看清除浮动后的样子:

方式一:设置高度

给浮动元素的父容器设置高度。

1
2
3
4
<div class="father">
<div class="left">left</div>
<div class="right">right</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.father {
border: 1px solid red;
width: 300px;
height:200px;
}
.left {
width: 100px;
height: 100px;
float: left;
background-color: blue;
}
.right {
width: 100px;
height: 100px;
float: right;
background-color: yellow;
}

方式二:添加空标签

在浮动元素下方添加空 div,并使用 clear: both;

1
2
3
4
5
<div class="father">
<div class="left">left</div>
<div class="right">right</div>
<div class="clear"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.father {
border: 1px solid red;
width:300px;
}
.left {
width: 100px;
height: 100px;
float: left;
background-color: blue;
}
.right {
width: 100px;
height: 100px;
float: right;
background-color: yellow;
}
.clear {
clear: both;
}

方式三:使用overflow

给浮动元素的父容器添加 overflow: hidden; 或者 overflow: auto;

1
2
3
4
<div class="father">
<div class="left">left</div>
<div class="right">right</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.father {
border: 1px solid red;
width: 300px;
overflow: auto;
}
.left {
width: 100px;
height: 100px;
float: left;
background-color: blue;
}
.right {
width: 100px;
height: 100px;
float: right;
background-color: yellow;
}

方式四:添加伪元素

给浮动元素的父容器添加 clearfix 的 class,用伪元素 clearfix:after 设置样式,清除浮动。

1
2
3
4
<div class="father clearfix">
<div class="left">left</div>
<div class="right">right</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.father {
border: 1px solid red;
width: 300px;
}
.left {
width: 100px;
height: 100px;
float: left;
background-color: blue;
}
.right {
width: 100px;
height: 100px;
float: right;
background-color: yellow;
}
.clearfix::after {
content: '';
display: block;
clear: both;
}
.clearfix {
zoom: 1; // 兼容IE
}