什么是层叠上下文?z-index 的层叠规则是什么?
层叠上下文(Stacking Context)是 CSS 中决定元素在 z 轴上渲染顺序的概念。
创建层叠上下文的条件
- 根元素
<html>(天然是层叠上下文) - position 非 static + z-index 非 auto
- opacity < 1
- transform 非 none
- filter 非 none
- will-change 设为上述属性
- isolation: isolate
- mix-blend-mode 非 normal
display: flex/grid子项 + z-index 非 auto
层叠顺序(从低到高)
1. 层叠上下文的背景和边框
2. 负 z-index
3. 块级盒子(正常流)
4. 浮动盒子
5. 行内盒子(正常流)
6. z-index: 0 / auto
7. 正 z-index关键规则
z-index 只在同一层叠上下文内比较!
<div style="position:relative; z-index:1">
<div style="position:relative; z-index:9999">A</div>
</div>
<div style="position:relative; z-index:2">
<div style="position:relative; z-index:1">B</div>
</div>- 父1 (z-index:1) vs 父2 (z-index:2) → 父2 在上
- 虽然 A 的 z-index:9999 很大,但它只在父1内部生效
- B 在 A 之上(因为父2 > 父1)
常见问题
1. 弹窗被遮挡
/* 如果父元素创建了层叠上下文,子元素的 z-index 再大也出不去 */
.parent {
transform: translateZ(0); /* 创建了层叠上下文 */
z-index: 1;
}
.modal {
z-index: 9999; /* 只在 parent 内部有效 */
}2. 解决方案
- 将弹窗移到父元素外面(Portal)
- 移除父元素创建层叠上下文的属性
- 提升父元素的 z-index
调试技巧
- Chrome DevTools → Elements 面板可查看层叠上下文
- 避免滥用 z-index,用 DOM 顺序和 flex/grid 的 order 代替