| 屬性 | 作用 | 常用值 |
|---|---|---|
| background-image | 背景圖片路徑 | url("path/to/img.jpg") |
| background-repeat | 平鋪方式 | repeat / no-repeat / repeat-x / repeat-y |
| background-attachment | 固定/捲動 | scroll(預設) / fixed / local |
| background-position | 定位基準點 | 關鍵字 / 百分比 / 長度 / 組合 |
| background-size | 縮放大小 | auto / cover / contain / 長度 / 百分比 |
.footer-bg {
background-image: url("/images/bg-footer.jpg");
background-repeat: no-repeat;
background-attachment: fixed; /* 相對視窗固定,捲動時視差效果 */
background-position: center bottom; /* 水平置中、垂直靠底 */
background-size: cover; /* 覆蓋容器,保持比例 */
min-height: 300px; /* 確保容器有高度顯示背景 */
}
left top | center top | right top
left center | center center | right center
left bottom | center bottom | right bottom
單一關鍵字會自動補另一軸為 center:bottom ≡ center bottom。
50% 50% 置中,100% 100% 右下角20px 30px = 右 20px、下 30pxright 20px bottom 10px(四值語法,現代瀏覽器支援)| 值 | 行為 | 適用場景 |
|---|---|---|
| scroll | 隨元素捲動(預設) | 一般內容區背景 |
| fixed | 相對視窗固定 | 視差滾動、全頁大圖、底部固定裝飾 |
| local | 隨元素內容捲動 | 可捲動容器內的背景圖案 |
⚠️ fixed 在 iOS Safari 早期版本有 Bug,現代版本已修復;移動端建議用 background-attachment: scroll + JS 視差或 position: sticky 替代。
/* 順序:color image repeat attachment position/size */
background: #f5f5f5 url("/images/bg.jpg") no-repeat fixed center bottom / cover;
/* ↑色彩 ↑圖片 ↑平鋪 ↑附著 ↑定位 ↑尺寸 */
footer {
position: relative;
padding: 4rem 0;
background:
linear-gradient(180deg, transparent, #fafafa 50%),
url("/images/wave-bottom.svg") no-repeat center bottom / 100% auto;
background-attachment: scroll; /* 移動端友善 */
}
掌握背景定位後,建議學習 CSS ID 與 Class 差異、用法與命名規範,建立清晰的樣式架構。