Quick overview of stacking context
Stacking context 決定元素在 z 軸上的堆疊順序,以下爲常見建立新的 stacking context 的情況:
- 根元素
<html> position: absoluteposition: fixedposition: stickyposition: relative且z-index不為autoopacity小於1- 使用
transform,scale,rotate - Flex item 且
z-index不為auto - Grid item 且
z-index不為auto will-change不為auto
核心規則:
<html>會自動形成一個 stacking context,當子元素若符合條件,也會形成新的 stacking context- 同一個 stacking context 中,元素依
z-index進行比較,z-index較大者在上方 - 若
z-index相同,後出現的元素會覆蓋先出現的元素 - Stacking context 內的元素只影響同層級內的堆疊,內外部互不干擾(適當隔離可以減少 reflow 及 repaint 的次數)
Basic example
html
<html><body><header style="position: sticky; z-index: 100;"><h1>Title</h1></header><section><h2>First section</h2><div>Item 1</div><div>Item 2</div></section><section style="position: absolute;"><h2>Second section</h2><div>Item 1</div><div>Item 2</div></section></body></html>

