z-index 僅對定位元素 (position ≠ static) 生效。 預設 position: static 時,z-index 被忽略。
.top-layer {
position: absolute; /* 或 relative, fixed, sticky */
z-index: 9999; /* 數值越大越上層 */
}
| position | 參考基準 | 適用場景 |
|---|---|---|
| relative | 自身原位置 | 微調佈局,建立 z-index 上下文 |
| absolute | 最近的非 static 祖先 | 彈窗、下拉選單、覆蓋層 |
| fixed | 視口 | 固定導航、回頂按鈕 |
| sticky | 視口 + 滾動容器 | 吸頂表頭 |
opacity < 1, transform, filter),子元素 z-index 無法跨越父層級比較。z-index,依 DOM 順序疊加。開發者工具 → Elements → Computed → 搜尋 z-index,查看實際生效值與堆疊上下文層級。