Back to notes

Quick overview of stacking context

Stacking context 決定元素在 z 軸上的堆疊順序,以下爲常見建立新的 stacking context 的情況:

  • 根元素 <html>
  • position: absolute
  • position: fixed
  • position: sticky
  • position: relativez-index 不為 auto
  • opacity 小於 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>

References