定位是 CSS 佈局的靈魂,也是阻擋無數初學者的門檻。本文以「專業定義 → 形象比喻 → 核心實例 → 綜合實戰」四層遞進,徹底攻克 `position: relative/absolute/fixed` 與盒模型交互規律。
| 定位類型 | 關鍵字 | 脫離文檔流 | 定位基準 | 層疊 |
|---|---|---|---|---|
| 靜態 | static | 否 | 正常流 | 無 |
| 相對 | relative | 否(佔位) | 自身原位置 | z-index |
| 絕對 | absolute | 是 | 最近已定位祖先 | z-index |
| 固定 | fixed | 是 | 視窗 viewport | z-index |
本文重點講解 相對定位 與 絕對定位 的組合拳。
.parent { width:200px; height:200px; background:#33CCFF; }
.child { width:100px; height:100px; background:#66CC66; }
子元素自然佔據父元素左上角,父元素撐開高度。
.child { position: absolute; top: 0; } /* 缺少 top/right/bottom/left 任何一個,定位不生效 */
.layer1 { position: absolute; z-index: 1; }
.layer2 { position: absolute; z-index: 2; } /* 覆蓋 layer1 */
.layer3 { position: absolute; z-index: -1; } /* ⚠️ Firefox 不支援負 z-index 顯示在父元素背景下

4. 相對定位不脫流,佔位偏移
.child { position: relative; top: 20px; left: 30px; }
視覺上移動,但原位置留白,後續元素不會填補。
5. 負值定位:突破邊界
.child { position: absolute; top: -10px; left: -10px; }
可將元素移出父容器視覺範圍(如工具提示尖角、徽章角標)。
四、實戰黃金法則:Relative 父 + Absolute 子
.parent { position: relative; } /* 建立定位上下文,自身不偏移 */
.child { position: absolute; top: 10px; right: 10px; } /* 精準定位在父元素右上角 */
應用場景:
- 圖片角標、徽章
- 下拉菜單定位
- 模態框關閉按鈕
- 輸入框清除圖標
- 工具提示定位
五、綜合實戰:CSS 相冊效果
利用 `relative` 容器 + `absolute` 圖片疊放 + `z-index` 排序 + `:hover` 縮放/旋轉,構建交互式相冊。核心代碼:
.album { position: relative; width: 400px; height: 300px; margin: 50px auto; }
.photo { position: absolute; top: 0; left: 0; width: 100%; height: 100%;
transition: transform .3s, z-index 0s .3s; }
.photo:nth-child(1) { z-index: 1; transform: rotate(-5deg) translate(-20px, -10px); }
.photo:nth-child(2) { z-index: 2; transform: rotate(3deg) translate(10px, -5px); }
.photo:nth-child(3) { z-index: 3; transform: rotate(-2deg); }
.photo:hover { z-index: 10; transform: rotate(0) scale(1.2); transition-delay: 0s; }
🎯 核心心法:Relative 造「場」,Absolute 占「位」,z-index 定「序」,負值破「界」。熟練組合這四招,佈局無不成。