BFC 全称 Block Formatting Context(块格式化上下文),是 CSS 视觉渲染的独立布局区域,可理解为一个 “封闭的布局容器”—— 容器内元素按规则布局,且内外互不干扰,是解决常见布局问题的核心机制。 出现 BFC(块格式化上下文)的核心是:元素满足任一特定条件,即可触发并生成 BFC(独立的布局隔离区域),常见触发场景(即 “什么时候出现 BFC”)如下:
-
浮动元素触发 BFC:元素设置
float: left或float: right(排除float: none)。 -
定位元素触发 BFC:元素设置
position: absolute或position: fixed(脱离常规文档流,自动生成 BFC)。 -
特定 display 值触发 BFC:
display: inline-block(行内块元素)display: flex/display: inline-flex(弹性布局容器)display: grid/display: inline-grid(网格布局容器)display: table-cell、display: table-caption、display: flow-root(特殊布局场景)
-
溢出相关设置触发 BFC:元素设置
overflow: hidden、overflow: auto或overflow: scroll(排除overflow: visible),是日常最常用的轻量触发方式。
如何解决
<!doctype html>
<html>
<head>
<style>
.parent {
border: 2px solid #f00;
width: 300px;
}
/* 子元素浮动 */
.child {
float: left;
width: 100px;
height: 100px;
border: 2px solid #f00;
margin: 5px;
}
/* 清除浮动万能公式 */
.clearfix::after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div class="parent clearfix">
<div class="child">浮动元素1</div>
</div>
</body>
</html>