Z-index 並非全域排序,而是在「層疊脈絡」內部比較。每個建立層疊脈絡的元素,其子孫元素的 z-index 只在該脈絡內比較,不受外部影響。
position: relative/absolute/fixed/sticky + z-index: 不為 autoopacity < 1transform/filter/perspective/clip-path/mask 不為 noneisolation: isolatewill-change 指定上述屬性z-index 不為 auto 的子元素<html> 根元素(Root Stacking Context)| 情境 | Firefox 3+ / 標準 | IE6/7 |
|---|---|---|
| 負 z-index vs 父背景 | 負 z-index 在父背景之上 | 負 z-index 在父背景之下 ❌ |
| Float vs Block 堆疊序 | Float 高於 Block | 同層級 ❌ |
| Inline 元素堆疊 | 在 Block 之上 | 在 Block 之下 ❌ |
<div class="parent" style="z-index: 1;">
<div class="child" style="z-index: 9999;">我還是會被外部 z-index:2 的元素蓋住</div>
</div>
<div class="sibling" style="z-index: 2;">我會蓋住 child</div>
子元素 z-index 再大,也只能在父脈絡內比較。若父脈絡 z-index 較低,子元素永遠無法超越較高的同級脈絡。
outline: 2px solid red 確認邊界isolation: isolate 強制建立新脈絡,隔離內部 z-index