在網頁排版與元素定位的過程中,position 和 z-index 是非常常見,但也容易令人混淆的 CSS 屬性。本文透過一段簡單的 HTML + CSS 範例,探討「子元素的位置」如何受到這些屬性的影響,並進一步解析 Stacking Context(堆疊上下文)的運作邏輯。
範例程式碼如下:
<div style = "position: relative; width: 300px; height: 300px; background: lightyellow; top: 150px; left: 250px; border: 2px solid; z-index: -2;">
<div style = "position: absolute; z-index: 77; top: 5px; left: 90px; width: 60px; height: 70px; background: lightgreen;">lll
<div style = "position: absolute; top: 8px; left: 20px; z-index: 89; width: 300px; height: 30px; background: violet;">AAAAAAAAAA</div>
</div>
<div style = "position: absolute; z-index: 88; left: 70px; top: 22px; width: 60px; height: 40px; background: lightblue;">BBBBB</div>
<div style = "position: absolute; z-index: 99; left: 80px; top: 33px; width: 60px; height: 40px; background: lightgray;">CCCCC</div>
</div>