CSS 格式化上下文与层叠规则详解
一、BFC(Block Formatting Context)
1.1 BFC 的形成条件
以下CSS属性可以创建一个新的BFC:
- 根元素(
<html>)
- 浮动元素(
float不为none)
- 绝对定位元素(
position为absolute或fixed)
display: inline-block | table-cell | table-caption
overflow不为visible的元素
display: flow-root(专门创建BFC,无副作用)
- Flex容器(
display: flex/inline-flex)
- Grid容器(
display: grid/inline-grid)
contain: layout | content | strict
- 多列容器(
column-count或column-width不为auto)
1.2 BFC 的核心特性
- 内部盒子垂直排列:BFC内的块级盒子会垂直方向一个接一个放置
- 边距不会合并:相邻盒子的垂直外边距不会合并
- 包含浮动元素:计算高度时会包含浮动子元素
- 隔离外部浮动:BFC区域不会与外部浮动元素重叠
- 独立布局环境:内部布局不影响外部,反之亦然
1.3 BFC 的实际应用
解决外边距合并
1 2 3
| .container { display: flow-root; }
|
清除浮动
1 2 3
| .clearfix { overflow: auto; }
|
防止文字环绕
1 2 3
| .content { overflow: hidden; }
|
二、IFC(行内格式化上下文)
2.1 IFC 的形成条件
当元素设置为display: inline | inline-block | inline-table等行内级元素时,会形成IFC。
2.2 IFC 的核心特性
- 水平排列:盒子在水平方向一个接一个排列
- 垂直对齐:通过
vertical-align属性控制对齐
- **行框(line box)**:每一行生成一个矩形区域包含该行所有内容
- 高度计算:由行高(
line-height)决定
- 断行规则:当宽度不足时会自动换行
2.3 IFC 的实际应用
垂直居中
1 2 3 4
| .container { height: 100px; line-height: 100px; }
|
基线对齐
1 2 3
| .icon { vertical-align: middle; }
|
文字环绕效果
1 2 3
| .text { display: inline; }
|
三、层叠上下文(z-index)
3.1 层叠上下文的形成条件
以下属性会创建新的层叠上下文:
- 根元素(HTML)
position: relative/absolute/fixed且z-index不为auto
position: fixed(无需z-index)
- Flex容器(
display: flex)且z-index不为auto
- Grid容器(
display: grid)且z-index不为auto
opacity小于1
transform不为none
filter不为none
will-change指定了特定属性
isolation: isolate
3.2 层叠顺序规则(从下到上)
- 层叠上下文的背景和边框
z-index为负的子元素
- 普通流中的块级元素
- 浮动元素
- 普通流中的行内元素
z-index: auto或0的定位元素
z-index为正的子元素
3.3 层叠上下文特性
- 局部作用域:子元素的z-index只在当前层叠上下文中有效
- 隔离性:不同层叠上下文的元素互不影响
- 绘制顺序:同级层叠上下文按z-index值排序
3.4 实际应用示例
解决z-index失效
1 2 3 4 5 6 7 8 9
| .parent { position: relative; z-index: 1; }
.child { position: absolute; z-index: 9999; }
|
模态框实现
1 2 3 4 5 6 7 8 9
| .modal { position: fixed; z-index: 1000; }
.overlay { position: fixed; z-index: 999; }
|
四、三者关系总结
| 特性 |
BFC |
IFC |
层叠上下文 |
| 布局方向 |
垂直 |
水平 |
垂直于屏幕(z轴) |
| 主要作用 |
块级元素布局 |
行内元素布局 |
控制元素显示层级 |
| 创建方式 |
特定CSS属性触发 |
行内级元素自动创建 |
特定CSS属性触发 |
| 典型应用 |
清除浮动、阻止边距合并 |
文字布局、垂直对齐 |
模态框、下拉菜单等层级控制 |