| 特性 | Relative (相對) | Absolute (絕對) |
|---|---|---|
| 文檔流 | ✅ 保留原空間 | ❌ 完全脫離 |
| 定位基準 | 自身原始位置 | 最近非 static 祖先 |
| 對周圍影響 | 無(佔位不變) | 無(不佔位) |
| 典型用途 | 微調、建立定位上下文、z-index 分層 | 彈層、圖標精準定位、固定定位 |
.shifted {
position: relative;
left: 40px; /* 視覺上向右移 40px */
top: 10px; /* 視覺上向下移 10px */
}
/* 實際佔據空間仍在原處,後續元素不會補位 */
top/right/bottom/left 為**視覺位移**,不改變盒模型佔位。left: 20px; right: 20px),left 優先(LTR 模式)。.icon { position: relative; top: 2px; } /* 圖標垂直置中微調 */
.badge { position: relative; top: -8px; right: -8px; } /* 徽章移至角落 */
.dropdown { position: relative; } /* 父級相對定位 */
.dropdown__menu { position: absolute; top: 100%; left: 0; } /* 子級絕對定位 */
.modal-overlay { position: relative; z-index: 100; }
.modal { position: relative; z-index: 101; } /* 確保彈窗在遮罩之上 */
默認值,元素按常規流排列,top/left/z-index **完全無效**。僅用於「重置」繼承來的定位屬性。
top: 50% 相對**父級高度**,若父級無高度則失效。transform 時,子級 position: fixed 相對父級而非視口定位。相對定位是「隱形膠水」:看似不動聲色,實則掌控著子元素的定位座標系、層疊順序與視覺微調。善用它建立錨點、配合 z-index 分層,是 CSS 佈局進階的必修課。