在 normal flow 下,position 要設定 static 以外的值,z-index 才有效。
*如果是用 flexbox 或是 grid 排版,可直接修改 item 的 z-index,不需要另外加 position: relative
<div class="container">
  <div class="item">I am item</div>
</div>
.container {
  width: 250px;
  height: 250px;
  background: rgb(232 240 254 / 0.5);
}
.container .item {
  position: relative;
  z-index: -1;
  width: 300px;
  background: pink;
}
container 元素 z-index 初始值為 auto,item 元素 z-index 為 -1,item 會被蓋在 container 底下
如果改成以下樣式
.container {
  position: relative;
  z-index: 0;
}
container 元素的 position 已經不是 static,且 z-index 也不是 auto,此時 container 會建立一個全新的 stacking context,即使現在把 item 的 z-index 設為 -999,item 也不會被蓋在 container 底下。
可以使用 opacity、will-change 或是 transform 等方式,來建立 stacking context,不一定要用 position + z-index
*建立 stacking context 的方式很多,可參考 MDN Web Docs - Stacking context
stacking context 像是把相同父層的元素集結在一起成為一個獨立環境,可以透過 z-index 來控制每一層在 z 軸的位置。

圖取自 x.com(Julia Evans) - z-index & stacking contexts
*同一個 stacking context 才會比較 z-index 值,適合拿來做圖層群組化