position: relative 讓元素相對其原始位置偏移,但原佔據空間保留,後續元素佈局不受影響。
.offset {
position: relative;
top: 10px; /* 向下位移 10px (視覺上) */
left: 40px; /* 向右位移 40px */
/* 原位置保留 10px×40px 空白區域 */
}
.icon-badge {
position: relative;
top: -4px; /* 圖示向上微調對齊文字光學中心 */
}
.card {
position: relative; /* 建立包含塊 */
padding: 1.5rem;
}
.card .badge {
position: absolute;
top: -8px;
right: -8px;
/* 相對 .card 內邊距盒定位 */
}
.dropdown {
position: relative; /* 建立層疊脈絡 */
z-index: 10; /* 在父脈絡中定層級 */
}
.dropdown-menu {
position: absolute;
z-index: 1; /* 僅在 .dropdown 脈絡內比較 */
}
.modal-overlay {
position: fixed;
inset: 0;
z-index: 1000;
background: rgba(0,0,0,0.5);
}
.modal {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
z-index: 1001; /* 高於 overlay */
}
| 特性 | Relative | Absolute | Fixed |
|---|---|---|---|
| 脫離文檔流 | 否 | 是 | 是 |
| 保留原空間 | 是 | 否 | 否 |
| 定位基準 | 自身原位置 | 最近定位祖先 | 視窗 (Viewport) |
| 建立層疊脈絡 | 是 (z-index ≠ auto) | 是 (z-index ≠ auto) | 是 (永遠) |
| 滾動行為 | 跟隨文檔滾動 | 跟隨最近定位祖先滾動 | 固定視窗,不隨滾動 |
.sticky-header {
position: sticky;
top: 0;
z-index: 100;
background: #fff;
/* 滾動到頂部時固定,未到時相對定位 */
}
top: 10px 以為是「距離頂部 10px」 → 實際是「向下位移 10px」:root {
--badge-offset: -8px;
}
.badge {
position: absolute;
top: var(--badge-offset);
right: var(--badge-offset);
}
/* 媒體查詢調整 */
@media (max-width: 480px) {
:root { --badge-offset: -4px; }
}