position: relative(相對定位)與 position: absolute(絕對定位)是 CSS 佈局核心,但常被誤解。本文從文檔流、偏移行為、參考物尋找、層疊順序、實戰模式五個維度深度解析,並附圖示說明。
top/right/bottom/left、z-index 完全無效top/right/bottom/left 相對「自身原位置」偏移

position ≠ static 的祖先元素(relative/absolute/fixed),作為定位基準;若無則以 <body> 為準(非視口)


| 特性 | relative | absolute |
|---|---|---|
| 文檔流佔位 | 保留 | 移除 |
| 偏移基準 | 自身原位置 | 最近非 static 祖先(padding box) |
| 影響兄弟元素 | 不影響(視覺覆蓋) | 不影響(兄弟元素補位) |
| 建立定位上下文 | 是 | 是 |
| 典型用途 | 微調位置、做絕對定位參考物 | 彈窗、下拉選單、工具提示、圖標定位 |
.parent { position: relative; }
.child { position: absolute; top: 0; right: 0; } /* 釘在父元素右上角 */
.card { position: relative; display: inline-block; }
.badge { position: absolute; top: -8px; right: -8px; background: red; color: white; border-radius: 50%; }
.dropdown { position: relative; }
.dropdown-menu { position: absolute; top: 100%; left: 0; min-width: 200px; }
top:0; left:0 卻無定位父層 → 會跑到 body 左上角transform: translate() 代替 top/left 做動畫,避免觸發 layout 重排掌握定位機制,是從「會切版」進階到「會架構版面」的關鍵門檻。