子元素设置浮动后,如果父元素没有给定高度,则会引起父元素的高度为0。
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
/* 子元素设置了浮动 */
.son1 {
background-color: powderblue;
float: left;
width: 100px;
height: 100px;
}
.son2 {
background-color: green;
float: right;
width: 100px;
height: 100px;
}
/* 父元素只有宽度,没有高度,希望由子元素撑开 */
.father {
width: 500px;
background-color: salmon;
}
如下图所示,父元素设置了背景色,但是并没有显示。
发现.father的盒模型的高度是0
解决:
当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现而进行的CSS处理,就叫CSS清除浮动。
方法1:clear:both;(不推荐)
在最后一个浮动的标签后添加一个空标签,并定义css属性clear:both;
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
<div class='clear'></div>
</div>
/* 子元素设置了浮动 */
.son1 {
background-color: powderblue;
float: left;
width: 100px;
height: 100px;
}
.son2 {
background-color: green;
float: right;
width: 100px;
height: 100px;
}
/* 父元素只有宽度,没有高度,希望由子元素撑开 */
.father {
width: 500px;
background-color: salmon;
}
/* 在最后一个浮动子元素后面添加的标签,并设置clear:both; */
.clear {
clear: both;
}
方法二:父元素添加overfolw:hidden;(不推荐)
/* 父元素只有宽度,没有高度,希望由子元素撑开 */
.father {
overflow: hidden;
width: 500px;
background-color: salmon;
}
方法三:单伪元素实现清除浮动(推荐)
/* 单伪元素实现清除浮动 */
.father::after {
content: '';
/*建议加个height:0*/
height: 0;
display: block;
clear: both;
visibility: hidden;
}
方法四:双伪元素实现清除浮动(推荐)
/* 双伪元素实现清除浮动 */
.father::after,
.father::before {
content: '';
display: table;
}
.father::after {
clear: both;
}
上述方法最后效果: