| 值 | 定位基準 | 脫離文檔流 | 佔據空間 | 典型用途 |
|---|---|---|---|---|
static | 正常文檔流 | 否 | 是 | 預設 |
relative | **自身原位置** | 否(視覺偏移) | **是**(保留原空間) | 微調、定位基準、z-index 基準 |
absolute | **最近定位祖先** | 是 | 否 | 彈層、圖標、精確佈局 |
fixed | **視窗** | 是 | 否 | 固定導航、回頂部、彈窗遮罩 |
sticky | 視窗/滾動容器 | 否→是(閾值切換) | 是 | 吸頂表頭、側邊欄跟隨 |
.box {
position: relative;
left: 30px;
top: 20px;
}
關鍵特性:
z-index 控制層級
.parent { position: relative; } /* 建立定位上下文 */
.child {
position: absolute;
top: 20px;
right: 10px;
}
關鍵特性:
position !== static 祖先元素(無則為初始包含塊)position: relative(不改變自身佈局)作為定位錨點position: relative)相對定位:西瓜在水中,用魔法偏移位置,但水中仍保留西瓜形狀的空洞(佔據空間),水流會繞開空洞。
絕對定位:西瓜被撈起掛在鉤子上(脫離水/文檔流),水自動填補空洞(不佔空間)。若水桶有定位,鉤子掛在桶上(相對父容器定位);否則掛在房間頂棚(相對視窗/文檔定位)。
.btn {
position: relative;
padding-left: 28px;
}
.btn::before {
content: '';
position: absolute;
left: 8px; top: 50%;
transform: translateY(-50%);
width: 16px; height: 16px;
background: url(icon.svg) no-repeat center / contain;
}
.avatar {
position: relative;
display: inline-block;
}
.badge {
position: absolute;
top: -4px; right: -4px;
min-width: 16px; height: 16px;
background: #e74c3c;
border-radius: 8px;
font-size: 10px;
color: #fff;
text-align: center;
line-height: 16px;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-menu {
position: absolute;
top: 100%; left: 0;
min-width: 160px;
background: #fff;
box-shadow: 0 4px 12px rgba(0,0,0,.15);
border-radius: 4px;
opacity: 0; visibility: hidden;
transform: translateY(-8px);
transition: all 0.2s;
}
.dropdown:hover .dropdown-menu {
opacity: 1; visibility: visible;
transform: translateY(0);
}
.modal-overlay {
position: fixed;
inset: 0; /* top:0; right:0; bottom:0; left:0; */
background: rgba(0,0,0,.5);
z-index: 1000;
}
.modal-content {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
width: 90%; max-width: 500px;
background: #fff;
border-radius: 8px;
z-index: 1001;
}
| 坑點 | 原因 | 解決 |
|---|---|---|
| absolute 子元素相對 body 定位 | 無定位祖先 | 父元素加 position:relative |
| fixed 元素在 transform 父元素內定位異常 | transform 建立新包含塊 | 避免在 fixed 祖先上加 transform,或改用 absolute |
| z-index 不生效 | 未建立堆疊上下文 | 父元素加 position + z-index,或用 isolation:isolate |
| sticky 不生效 | 祖先 overflow:hidden/auto/scroll | 祖先 overflow:visible 或改用 fixed |
| absolute 元素撐開父容器 | 絕對定位脫離流 | 父容器設 min-height、或用 Grid/Flex |
相對定位「佔坑不讓人」,絕對定位「脫離不佔坑」。掌握 **定位上下文(Containing Block)**、**堆疊上下文**、**文檔流脫離與保留** 三大核心機制,配合 transform/z-index/inset 現代屬性,即能駕馭從簡單微調到複雜分層 UI 的所有定位需求。記住:能用 Flex/Grid 解決的佈局,絕不動用定位。