CSS 层叠上下文隔离 z-index
快速摘要
你给子元素设 z-index: 9999 但它仍在模态之下——父元素创建了新层叠上下文,隔离了子元素的 z-index。
为什么发生
祖先有 transform、opacity < 1、filter 或 will-change 创建层叠上下文
子元素 z-index 仅在其层叠上下文内比较,非全局
另一上下文中 z-index 较低的模态仍胜出
最小示例
✗ 错误代码
.parent { transform: translateZ(0); /* creates stacking context */ }
.child { z-index: 9999; /* cannot escape parent's context */ }
.modal { z-index: 100; /* in root context, wins over .child */ }✓ 修复代码
.parent { /* no transform — no new stacking context */ }
.child { z-index: 9999; /* compared in root context */ }
.modal { z-index: 100; }.parent 上的 transform 创建层叠上下文,.child 的 z-index 仅局部,无法胜过根上下文中的 .modal。去掉 transform 让 .child 全局竞争。
如何诊断
检查祖先链中创建层叠上下文的属性
比较上下文根的 z-index 而非仅叶元素
用 DevTools 查看层叠上下文层级
如何修复
把元素移出隔离层叠上下文(如 portal 到 body)
提高根化上下文的祖先 z-index
移除创建上下文的属性(transform、opacity)
如何预防
知道 transform、opacity、filter 会创建层叠上下文
模态与提示框 portal 到 body 以逃出嵌套上下文