iT邦幫忙

2021 iThome 鐵人賽

0
自我挑戰組

登堂入室!前端工程師的觀念技術 _30_ 題系列 第 31 篇

30. CSS 的 z-index & Stacking Context 的形成

  • 分享至 

  • xImage
  •  

Stacking Context


定義

Stacking Context是指對於HTML元素而言,有一個面向使用者的假想軸(z軸),
而元素會依據設定好的屬性,沿著軸進行排列順序,使元素產生堆疊。

The stacking context is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user, who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes.

在 27. 解釋 CSS 的 BFC(Block Formatting Context) 有提到,頁面裡的元素,預設會形成Block Formatting Context,並依照BFC的性質進行排版。

比較兩者的話,可以想成對使用者而言:

  • Formatting Context 是對二維方向的排列(x軸/y軸) → 預設為由上而下、由左而右排列。
  • Stacking Context 則是三維方向的堆疊(z軸) → 決定面向使用者(視窗)的堆疊順序。

性質

特定元素會受到z-index值而影響堆疊順序,原因是這些元素形成了Stacking Context。

... the rendering order of certain elements is influenced by their z-index value. This occurs because these elements have special properties which cause them to form a stacking context.

會形成Stacking Context的情況包括:

  • Root element of the document <html>
  • position 為 absolute/ relative 且 設定z-index
  • position 為 fixed/ sticky
  • flex/ grid container 的 child element 且 設定z-index
  • opacity值 < 1
  • 有設定 transform

z-index

  • 預設值為 0
  • 可以為負值,數字越小離使用者越遠,反之越近。
  • z-index 在 position 不為預設值(static)時有效。

可以把 z-index 的值想成是渲染順序:
先渲染1,然後渲染2,所以較晚渲染(數字較大)的元素會越靠上/靠近使用者。

這裡借用MDN的範例:
https://ithelp.ithome.com.tw/upload/images/20211012/20129476FiONyXTLaH.png

層級關係:

  • div1 z-index:5;
  • div2 z-index:2;
  • div3 z-index:4;
    • div4 z-index:6;
    • div5 z-index:1;
    • div6 z-index:3;
  1. Stacking Context在不同層級的間各自獨立
    → 意思是,不同層級的元素,z-index值並不互相影響。
    以上面設定的順序而言,並不會從數字最小的div5開始渲染,而是從div1,2,3取最小值開始進行渲染。

  2. 沒有產生Stacking Context的元素,會被父元素的Stacking Context同化(assimilated)。
    → 要注意**z-index的屬性不會繼承**,以範例而言,div4如果沒有設定z-index,就是0,並不會是從div3繼承4。

因此可以推導出渲染順序(堆疊順序):
div2 (2) -> div3 (4) -> div5(4.1) -> div6(4.3) -> div4(4.6) -> div1(5)

【如內文有誤還請不吝指教>< 並感謝閱覽至此的各位:D 】

參考資料


上一篇
29. CSS 水平置中/ 垂直置中的方法
系列文
登堂入室!前端工程師的觀念技術 _30_ 題 共 31 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言