浮动溢出 —— 当未设置容器的高度,且容器的子元素中有浮动的元素时,容器的高度不能自动伸长以适应内容的高度,从而导致内容溢出到容器外面而影响布局的现象

1
2
3
<div id="father">
<div id="son"></div>
</div>
1
2
3
4
5
6
7
8
9
#father {
width: 100%;
border: 2px solid red;
}
#father #son {
float: right;
width: 200px;
height: 200px;
background: yellowgreen;

为了防止浮动溢出的出现,我们需要进行浮动清除

设置父元素的高度

可以通过给父元素设置一个固定的高度包裹住子元素,但这种方法扩展性差,一旦内部高度发生变化就需要重新计算父元素高度


1
2
3
4
5
6
7
8
9
10
11
#father {
width: 100%;
height: 204px;
border: 2px solid red;
}
#father #son {
float: right;
width: 200px;
height: 200px;
background: yellowgreen;
}

添加标签并设置 clear

在父元素的最后一个子元素之后再添加一个块级元素,并设置clear: both


1
2
3
4
<div id="father">
<div id="son"></div>
<div style="clear:both;"></div>
</div>

伪元素清除浮动

给浮动元素的父容器添加一个::after伪元素,实现元素末尾添加一个看不见的块元素来清理浮动


1
2
3
<div id="father">
<div id="son"></div>
</div>
1
2
3
4
5
#father::after {
content: '';
display: block;
clear: both;
}

父元素设置 overflow

通过让父容器形成了 BFC(块级格式上下文),而 BFC 可以包含浮动,通常用来解决浮动父元素高度坍塌的问题


1
2
3
#father {
overflow: hidden;
}

br 标签

br标签存在一个属性clear,在br标签中设置属性clear="all"即能清除掉浮动


1
2
3
4
<div id="father">
<div id="son"></div>
<br clear="all" />
</div>