/* 關鍵字 */
background-position: top left;
background-position: center center;
background-position: bottom right;
/* 長度值(絕對/相對) */
background-position: 20px 40px;
background-position: -10px 0; /* 負值:圖片向左/上移動 */
/* 百分比值(關鍵:容器與圖片的對應點對齊) */
background-position: 50% 50%; /* 容器中心點對齊圖片中心點 */
background-position: 100% 100%; /* 容器右下角對齊圖片右下角 */
/* 混合單位 */
background-position: 20px center;
background-position: right 20px bottom 10px; /* CSS3 四值語法:邊距偏移 */
公式:容器內側邊距寬度 × 百分比 = 圖片寬度 × 百分比
0% 0%:圖片左上角貼齊容器左上角。50% 50%:圖片中心點對齊容器中心點(完美置中)。100% 100%:圖片右下角貼齊容器右下角。**負值效果**:background-position: -10px 0 → 圖片向左移動 10px,容器可視區域顯示圖片右側部分。
/* 從右邊向左偏移 20px,從底部向上偏移 10px */
background-position: right 20px bottom 10px;
/* 等同於 */
background-position: calc(100% - 20px) calc(100% - 10px);
支援:Chrome 25+、Firefox 13+、Safari 7+、Edge 12+、IE11+(部分)。
.icon {
display: inline-block;
width: 24px;
height: 24px;
background: url(sprite.png) no-repeat;
background-size: 240px auto; /* 精靈圖總寬 240px,10 個圖標 */
}
/* 第 1 個圖標 (0, 0) */
.icon-home { background-position: 0 0; }
/* 第 2 個 (-24px, 0) */
.icon-user { background-position: -24px 0; }
/* 第 3 個 (-48px, 0) */
.icon-settings { background-position: -48px 0; }
/* 第二行第一個 (0, -24px) */
.icon-mail { background-position: 0 -24px; }
.hero {
background: url(hero.jpg) center center / cover no-repeat;
/* 縮寫:position / size repeat */
height: 60vh;
min-height: 400px;
}
/* 多背景層疊 */
.layered-bg {
background:
url(pattern.png) 0 0 / 100px repeat,
url(hero.jpg) center / cover no-repeat,
linear-gradient(45deg, rgba(0,0,0,.4), transparent);
}
@keyframes pan-bg {
0% { background-position: 0 0; }
100% { background-position: 100% 0; } /* 水平滾動 */
}
.animated-bg {
background: url(panorama.jpg) repeat-x;
background-size: auto 100%;
animation: pan-bg 20s linear infinite;
}
height: auto 且無內容撐開)。解決:給容器固定高度或 min-height。background-size 或媒體查詢切換。background-size 精確控制。background-attachment: fixed 在移動端表現異常(iOS Safari 固定在視口)。建議用偽元素 ::before 模擬。background: url() center/cover no-repeat 縮寫。picture + source media 響應式載入,而非 CSS 背景圖。background-position: var(--bg-x, 50%) var(--bg-y, 50%)。background-position 掌控背景圖片在容器中的對齊方式。**百分比值基於「容器與圖片對應點對齊」原理**,負值實現圖片偏移。精靈圖仍是圖標系統方案,但現代項目建議遷移至 SVG/Icon Font。配合 background-size、background-attachment、多背景層疊、CSS 動畫,能實現極豐富的視覺效果。