position: absolute 讓元素脫離文檔流,相對「最近的已定位祖先」 (position ≠ static) 進行偏移定位。若無此類祖先,相對 初始包含塊 (ICB) — 通常是視窗或 <html>。
.positioned {
position: absolute;
top: 43px; /* 距基準上邊緣 */
right: 20px; /* 距基準右邊緣 */
bottom: auto; /* 預設 auto,由 top + height 決定 */
left: 100px; /* 距基準左邊緣 */
}
position: relative | absolute | fixed | sticky 的祖先| 屬性 | 百分比參考基準 |
|---|---|
| top, bottom, margin-top, margin-bottom, padding-top, padding-bottom | 包含塊 高度 |
| left, right, margin-left, margin-right, padding-left, padding-right | 包含塊 寬度 |
| width, height, max-width, min-height 等 | 包含塊對應 寬度/高度 |
| transform: translate() | 元素自身 寬度/高度 |
⚠️ 關鍵:垂直方向 margin/padding 百分比也是相對包含塊寬度,非高度!
.parent { /* 無 position */ }
.child { position: absolute; top: 20px; left: 20px; }
/* 子元素相對 body 定位,非父元素 */
修正:.parent { position: relative; } (不影響佈局)
.parent { position: relative; height: auto; }
.child { position: absolute; top: 50%; height: 50%; }
/* top: 50% 計算值為 0 (auto 視為 0) → 定位錯誤 */
修正:父元素給定確定高度,或改用 Flex/Grid 置中
.parent { position: relative; z-index: 1; }
.child { position: absolute; z-index: 9999; }
.sibling { position: relative; z-index: 2; }
/* sibling 蓋住 child,因比較在根脈絡層級 */
| 場景 | 傳統 Absolute | 現代方案 | 優勢 |
|---|---|---|---|
| 水平垂直置中 | top:50%; left:50%; transform:-50% | Flex: place-items:center / Grid: place-items:center | 無需定位、自適應內容尺寸 |
| 固定吸頂導航 | position:fixed; top:0 | position:sticky; top:0 | 無需固定高度、滾動邊界自動處理 |
| 彈出層/下拉選單 | absolute + z-index 管理 | Portal (React/Vue) + Floating UI | 脫離 DOM 層級限制、智能定位、無障礙 |
| 工具提示 | absolute + 手動定位 | Floating UI / Popper.js | 自動翻轉、邊界檢測、虛擬定位 |
| 模態框 | fixed + 高 z-index | <dialog> 元素 + ::backdrop | 原生語意、焦點陷阱、ESC 關閉 |
will-change: transform 觸發合成層contain: layout painttop/left 重排,改用 transform