z-index 與 stacking context

YY
2 min readMar 12, 2021
Photo by Holly Stratton on Unsplash

小時候(?)總以為 z-index 大的就比較邱可以蓋住別人,沒有 z-index: 999 解決不了的事,如果有,就 z-index: 9999

直到每次遇到類似問題要解,都要再重新到處翻資料複習一下這些蓋來蓋去的原則,還是自己來筆記一下好了

TL;DR

  1. z-index 作用於 positioned 元素
  2. 圖層排列 (bottom -> top)
  • stacking context root
  • positioned w/ negative z-index
  • non-positioned (source code order)
  • positioned w/o z-index (source code order)
  • positioned w/ positive z-index

3. 建立 stacking context

  • <html>
  • position is absolute || relative && z-index !== auto
  • position is fixed || sticky
  • flex children w/ z-index
  • grid children w/ z-index
  • opacity < 1
  • transform !== none

4. z-index 只在所屬的 stacking context 中比較

z-index

設定元素 z 方向的高度/圖層,只能設定於 positioned 元素,即 position 設為 static 外之值

預設值為 auto,對於 absolute、relative 元素設定 z-index 值將在其元素建立新的 stacking context

Stacking Context

簡單來說就是一個堆疊環境,在這個環境內的元素可以利用 z-index 互相比較圖層高低,但無法跟環境外的元素比較,只能透過建立這個 stacking context 的元素跟其所屬的 stacking context 中其他元素比較

source: MDN

如上圖中,DIV#3 建立了 stacking context,而其中 #4 #5 #6 可透過 z-index 做比較,但就算 DIV#4 的 z-index: 6 大於 DIV#1 仍然無法蓋過,因為 #3 才是跟 #1 屬於同個 stacking context

建立 stacking context

- Root element of the document (<html>).
- Element with a position value absolute or relative and z-index value other than auto.
- Element with a position value fixed or sticky (sticky for all mobile browsers, but not older desktop).
- Element that is a child of a flex container, with z-index value other than auto.
- Element that is a child of a grid container, with z-index value other than auto.
- Element with a opacity value less than 1 (See the specification for opacity).
- Element with a mix-blend-mode value other than normal.
- Element with any of the following properties with value other than none:
transformfilterperspectiveclip-pathmask / mask-image / mask-border
- Element with a isolation value isolate.
- Element with a -webkit-overflow-scrolling value touch.
- Element with a will-change value specifying any property that would create a stacking context on non-initial value (see this post).
- Element with a contain value of layout, or paint, or a composite value that includes either of them (i.e. contain: strict, contain: content).

Ref

--

--