position: absolute 元素:
<html> 或 viewport).box {
position: absolute;
top: 43px; /* 距定位基準上邊緣 */
right: 20px; /* 距定位基準右邊緣 */
bottom: auto; /* 預設 auto,由 top/height 決定 */
left: 100px; /* 距定位基準左邊緣 */
}
position 為 relative/absolute/fixed/sticky<div class="parent">
<div class="child" style="position:absolute; top:20px; left:20px">內容</div>
</div>
/* 父元素無 position → child 相對 body 定位 */
修正:.parent { position: relative; } (不改變佈局)
top/left/bottom/right 百分比:相對「包含塊」的 高度/寬度width/height 百分比:相對「包含塊」的 寬度/高度margin/padding 百分比:皆相對包含塊寬度 (含垂直方向!).parent { position: relative; z-index: 1; }
.child { position: absolute; z-index: 9999; } /* 只在 parent 脈絡內比較 */
.sibling { position: relative; z-index: 2; } /* 蓋住 child! */
| 需求 | 現代方案 | 優勢 |
|---|---|---|
| 置中對齊 | Flexbox place-items:center | 無需定位、自適應 |
| 固定吸頂/吸底 | position: sticky | 無需 JS、效能佳 |
| 彈出層/Modal | Fixed + Portal (React/Vue) | 避免 z-index 衝突、語意清晰 |
| 工具提示 | Floating UI / Popper.js | 自動翻轉、邊界檢测、無障礙 |
will-change: transform 或 transform: translateZ(0))contain: layout paint 隔離重排