593 字
3 分鐘
CSS z-index 設到 9999 還被蓋住?先找父層堆疊情境
本文目錄
選單的 z-index 已經設成 9999,還是被旁邊卡片蓋住,先在 DevTools 比較兩者的祖先。當選單和卡片分屬不同的堆疊情境(stacking context),在共同的外層參與比較的是各自的堆疊情境。 選單可以排在自己卡片內所有內容的前面,整張卡片仍可能畫在另一張的後面。 CSS 2.2:堆疊情境的繪製順序
在同一個重疊點檢查誰在上層
把這段存成 HTML。紫色選單是藍卡片的子元素,兩張卡片在同一個外層。用 elementFromPoint() 在兩個盒子都覆蓋的位置檢查最上方可命中的元素。
<!doctype html><meta charset="utf-8"><title>z-index 堆疊量測</title><style> body { margin: 0; } .card { position: absolute; top: 20px; width: 180px; height: 120px; } #left { left: 20px; z-index: 1; background: #a4d8f4; } #right { left: 220px; z-index: 2; background: #92d5ac; } #menu { position: absolute; left: 140px; top: 32px; z-index: 9999; width: 140px; height: 60px; background: #c5aff8; } pre { position: absolute; top: 160px; }</style><div class="card" id="left"><div id="menu">選單</div></div><div class="card" id="right">相鄰卡片</div><pre id="report"></pre><script> const left = document.querySelector('#left'); const menu = document.querySelector('#menu'); const topId = () => document.elementFromPoint(240, 60).id; const rows = [topId()]; menu.style.zIndex = '100000'; rows.push(topId()); left.style.zIndex = '3'; rows.push(topId()); left.style.zIndex = 'auto'; rows.push(topId()); left.style.zIndex = ''; menu.style.zIndex = ''; document.querySelector('#report').textContent = rows.join(' → ');</script>結果是 right → right → menu → menu。第三次量測把藍卡片整層抬高,第四次讓範例中的藍卡片退出自己的堆疊情境,紫色選單因此能在外層參與比較。第四種改法取決於祖先是否還有其他建立堆疊情境的屬性,例如 transform、小於 1 的 opacity 或 isolation: isolate。 MDN:堆疊情境
保留卡片順序,或只把浮層顯示在最上面
如果整張卡片在展開時都應浮到前面,就調整卡片那一層的順序。若只有選單要跨卡片,移到共同的浮層容器,或採用適合互動語意的 HTML Popover。移動後仍要檢查位置、鍵盤操作與關閉行為。 HTML Popover 實作
還有一個容易混淆的狀況。若選單即使在空白處也沿著容器邊界被整齊切斷,先暫停該祖先的 overflow: hidden 或 overflow: clip 做對照。上面的範例刻意沒有裁切規則;提高堆疊順序的結果只適用於被別的元素遮住的情況。
參考資料:
CSS z-index 設到 9999 還被蓋住?先找父層堆疊情境
https://laplusda.com/posts/css-z-index-parent-stacking-context/