
理解 Stacking Context:让 z-index 乖乖听话!
在前端开发中,你可能遇到过 z-index 失效的情况,调了半天 z-9999 结果还是被盖住?这通常是 Stacking Context(层叠上下文) 在作怪!
今天我们就用简单易懂的方式,搞懂 Stacking Context,让 z-index 彻底听话!
📌 什么是 Stacking Context?
Stacking Context 直译过来是 “层叠上下文”,可以理解为 一座独立的小楼,每个楼层(context)里,元素按照 z-index 的大小排队。
但重点是——每个楼都是独立的,A 楼的 z-index 不会影响 B 楼,就算你在 A 楼 z-9999,也可能还是被 B 楼的 z-1 盖住!
🎯 什么情况会创建新的 Stacking Context?
如果元素符合以下条件之一,它就会变成一个“新楼”(新的 Stacking Context):
1️⃣ z-index 不为 auto 且 position: relative | absolute | fixed | sticky
.box {
position: relative;
z-index: 10; /* 触发新的 Stacking Context */
}
2️⃣ isolation: isolate (强制创建新楼,防止 z-index 受父级影响)
.box {
isolation: isolate;
}
3️⃣ opacity 小于 1(哪怕是 0.99 也会触发!)
.box {
opacity: 0.99; /* 触发新的 Stacking Context */
}
4️⃣ transform, filter, clip-path, perspective 这些属性
.box {
transform: translateY(10px); /* 触发新的 Stacking Context */
}
5️⃣ mix-blend-mode(影响混合模式)
.box {
mix-blend-mode: multiply;
}
🤔 为什么 z-index 有时候失效?
假设你写了下面的代码:
<div className="relative z-10 bg-gray-300 p-4">
<div className="absolute inset-0 bg-blue-500 z-20">我是 z-20,为什么没生效?</div>
</div>
❌ 为什么 z-20 没生效?
因为 z-index 只在同一个 Stacking Context 内生效,但 .relative 父级如果 z-index: auto,它就没有创建新的 Stacking Context,那么 .absolute 子元素的 z-20 可能就不起作用!
✅ 解决方案
给 .relative 父级 显式设置 z-index 或 使用 isolation: isolate 让它变成独立 Stacking Context:
<div className="relative z-10 isolate bg-gray-300 p-4">
<div className="absolute inset-0 bg-blue-500 z-20">现在 z-20 终于生效了!</div>
</div>
🔍 结论
✅ z-index 只有在同一个 Stacking Context 里才能比较大小
✅ 新 Stacking Context 就像一个独立的楼层,z-index 只在自己楼里生效
✅ 如果 z-index 失效了,看看是不是被 Stacking Context 影响了
✅ 用 isolation: isolate 让 z-index 彻底独立
💡 z-index 失效?试试这些排查方法!
1️⃣ 检查父级有没有触发新的 Stacking Context?
- 看看
position + z-index - 看看
opacity,transform,filter,clip-path
2️⃣ 用 isolation: isolate 让当前元素创建自己的 Stacking Context
3️⃣ 如果是全屏遮罩,直接用 fixed 让它脱离 Stacking Context
.overlay {
position: fixed;
z-index: 9999;
}
这下 z-index 终于不会乱跑了吧?🚀 赶紧去项目里试试!💡
这里还有大神一篇很详细**的文章地址**,可以进一步学习
订阅 FreeMac
每周精选:Mac 高效技巧、免费替代付费软件、开发者工具推荐。用对你的 MacBook,省钱 + 提效。