问题现象
父元素包含多个浮动子元素时,父元素高度变为0,背景色/边框无法显示,后续元素被浮动元素覆盖。
深层原因
CSS浮动的特性是脱离文档流,浮动元素不参与父元素的高度计算,导致父元素无法感知子元素的高度。
分步解决方案(按推荐程度排序)
方案1:用Flex/Grid布局替代浮动(推荐,彻底解决)
父元素设置display: flex,子元素无需浮动,父元素会自动适应子元素高度:
html
<div class="parent">
<div class="child">子元素1</div>
<div class="child">子元素2</div>
</div>
<style>
.parent {
display: flex;
background: #f0f0f0; /* 父元素背景正常显示 */
}
.child {
width: 100px;
height: 100px;
background: #ff4400;
margin: 10px;
/* 无需float: left */
}
</style>
方案2:使用clearfix伪类(通用兼容方案)
给父元素添加clearfix类,通过伪元素清除浮动:
css
/* 通用clearfix(兼容所有浏览器) */
.clearfix::after {
content: "";
display: table; /* 触发BFC,避免外边距折叠 */
clear: both; /* 清除左右浮动 */
visibility: hidden;
height: 0;
}
/* 兼容IE6/7 */
.clearfix {
*zoom: 1;
}
/* 使用 */
.parent {
background: #f0f0f0;
}
.child {
float: left;
width: 100px;
height: 100px;
margin: 10px;
}
html
<div class="parent clearfix">
<div class="child">子元素1</div>
<div class="child">子元素2</div>
</div>
方案3:开启父元素BFC(简单但有副作用)
BFC的特性是包含浮动元素,计算高度时会包含浮动子元素。开启BFC的方式:
css
.parent {
overflow: hidden; /* 开启BFC(简单,但可能裁剪溢出内容) */
background: #f0f0f0;
}