小時候(?)總以為 z-index 大的就比較邱可以蓋住別人,沒有 z-index: 999 解決不了的事,如果有,就 z-index: 9999
直到每次遇到類似問題要解,都要再重新到處翻資料複習一下這些蓋來蓋去的原則,還是自己來筆記一下好了
TL;DR
- z-index 作用於 positioned 元素
- 圖層排列 (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 中其他元素比較
如上圖中,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 aposition
valueabsolute
orrelative
andz-index
value other thanauto
.
- Element with aposition
valuefixed
orsticky
(sticky for all mobile browsers, but not older desktop).
- Element that is a child of a flex container, withz-index
value other thanauto
.
- Element that is a child of agrid
container, withz-index
value other thanauto
.
- Element with aopacity
value less than1
(See the specification for opacity).
- Element with amix-blend-mode
value other thannormal
.
- Element with any of the following properties with value other thannone
:
—transform
、filter
、perspective
、clip-path
、mask
/mask-image
/mask-border
- Element with aisolation
valueisolate
.
- Element with a-webkit-overflow-scrolling
valuetouch
.
- Element with awill-change
value specifying any property that would create a stacking context on non-initial value (see this post).
- Element with acontain
value oflayout
, orpaint
, or a composite value that includes either of them (i.e.contain: strict
,contain: content
).