top/right/bottom/left 相對「自身原位置」偏移,視覺上移動,實際佔據空間不變。z-index 非 auto 時創建新層疊上下文。<style>
.box { width: 100px; height: 100px; background: #3498db; color: #fff; display: inline-block; }
.pos-left { position: relative; left: -20px; background: #e74c3c; }
.pos-right { position: relative; left: 20px; background: #2ecc71; }
</style>
<div class="box">正常位置</div>
<div class="box pos-left">向左位移 20px</div>
<div class="box pos-right">向右位移 20px</div>
<p>觀察:三個盒子在文檔流中位置不變,紅/綠盒視覺偏移但原佔位空間保留。</p>
.icon { position: relative; top: 2px; } /* 圖標與文字光學對齊 */
.input-suffix { position: relative; left: -30px; z-index: 1; } /* 輸入框後綴內嵌 */
.parent { position: relative; } /* 建立定位上下文 */
.child { position: absolute; top: 0; right: 0; } /* 相對父元素定位 */
這是「相對定位最核心價值」—— 為子孫絕對定位提供座標系。
.modal-overlay { position: fixed; z-index: 1000; }
.toast { position: relative; z-index: 1100; } /* 覆蓋彈窗 */
.slide-in {
position: relative;
animation: slide 0.3s ease-out;
}
@keyframes slide {
from { transform: translateX(-100%); } /* 合成器線程處理,無回流 */
to { transform: translateX(0); }
}
優於直接動畫 left:transform 不觸發佈局/繪製,僅合成。
| 誤區 | 真相 | 正確做法 |
|---|---|---|
| 以為相對定位會脫離文檔流 | 不脫離,原空間保留 | 需脫離流用 absolute/fixed |
| 用 relative + left/right 實現水平居中 | 需知寬度、且原空間保留 | margin-inline:auto / flex / grid |
| 父相對 + 子絕對,父無高度塌陷 | 絕對定位子脫離流,不撐開父級 | 父級設 min-height / 內容撐開 / 佈局替代 |
| 大量元素用 relative 佈局 | 層疊上下文爆炸、渲染開銷大 | 僅作定位參考點或微調,佈局用 Flex/Grid |
| left:50% + margin-left:-50% 居中 | 需知寬度、不響應式 | transform:translateX(-50%) 無需寬度 |
需要脫離文檔流?
├─ 否 → 需微調/作定位參考 → position:relative
└─ 是 → 需固定視口 → position:fixed
├─ 需跟隨滾動容器 → position:sticky
└─ 需相對最近定位祖先 → position:absolute
相對定位是 CSS 定位體系的「樞紐」:既是微調工具,又是絕對定位的錨點,更是層疊上下文的創建者。精準理解其「佔位不動、視覺位移」雙重特性,是佈局進階的必修課。