| 值 | 定位基準 | 脫離文件流 | 典型用途 |
|---|---|---|---|
| static | 正常文件流 | 否 | 預設值,不定位 |
| relative | 自身原位置 | 否(佔位保留) | 微調位置、建立 absolute 參考點 |
| absolute | 最近的非 static 祖先 | 是 | 精確定位、彈窗、Tooltip、圖示疊加 |
| fixed | 視窗 | 是 | 固定導覽、回到頂端、浮動按鈕 |
元素仍佔據原空間,視覺上按 top/right/bottom/left 偏移。後續元素位置不受影響。
.box {
position: relative;
top: 20px; left: 10px; /* 相對原位置向下 20px、向右 10px */
}
⚠️ 偏移基準為 margin 邊界外緣。
元素完全脫離文件流,不佔空間。定位基準為「最近的 position !== static 祖先元素」,若無則以 body(視窗)為準。
參考祖先的 padding 邊界(非 margin、非 border),即 content-box 起始點。
absolute 元素脫離流後,後續兄弟元素會「補位」佔據其原空間。
特殊的 absolute:永遠以視窗為基準,滾動不動。常用於固定導覽列、浮動客服按鈕。
.floating-btn {
position: fixed;
right: 24px; bottom: 24px;
z-index: 1000;
}
⚠️ 當祖先元素有 transform、filter、perspective 等屬性時,fixed 會改以該祖先為基準(建立新的 containing block)。
預設值,元素按正常文件流排列,top/right/bottom/left/z-index 無效。
.card {
position: relative;
}
.card::before {
content: "";
position: absolute;
inset: 0;
background: rgba(0,0,0,.4);
}
.card-content {
position: relative; /* 保證文字在偽元素之上 */
z-index: 1;
}
header { position: fixed; top: 0; width: 100%; height: 60px; }
body { padding-top: 60px; }
inset: 0; margin: auto;(需固定寬高)-webkit-transform: translateZ(0) 強制 GPU 加速精通定位後,建議學習 CSS 自適應按鈕實作原理,結合定位與背景圖片技巧。