理解 CSS 背景定位的座標系統是精確控制的關鍵:
.move-left {
background: url('images/hh.gif') no-repeat -10px 0;
}
圖片相對容器向左偏移 10px,右側會露出更多圖片內容。
.move-up {
background: url('images/hh.gif') no-repeat 0 -10px;
}
圖片相對容器向上偏移 10px,下方會露出更多圖片內容。
.move-right {
background: url('images/hh.gif') no-repeat 10px 0;
}
圖片相對容器向右偏移 10px,左側會露出容器背景色。
.move-down {
background: url('images/hh.gif') no-repeat 0 10px;
}
.move-diagonal {
background: url('images/hh.gif') no-repeat -10px -10px;
}
| 單位類型 | 適用場景 | 範例 |
|---|---|---|
| 像素 | 固定偏移、圖標精確對齊 | 10px 20px |
| 百分比 | 響應式佈局、相對容器定位 | 50% 50% (置中) |
| 關鍵字 | 語義化定位、快速原型 | top right, center |
| 混合使用 | 複雜定位需求 | right 20px bottom 10px (CSS3) |
.advanced-position {
/* 從右邊向左 20px,從底部向上 10px */
background-position: right 20px bottom 10px;
/* 等同於 */
background-position: calc(100% - 20px) calc(100% - 10px);
}
開發時可暫時添加 border: 1px solid red; 觀察容器邊界,或使用瀏覽器開發者工具的「計算樣式」面板即時調整數值預覽效果。