需求:背景圖片固定在容器底部顯示,不隨內容捲動(或捲動)。本文提供兩種寫法:縮寫屬性與拆解屬性,並說明各屬性作用。
.bottom-bg {
background: url(/images/bg.jpg) no-repeat fixed center bottom;
/* 顏色 圖片 重複 固定 水平位置 垂直位置 */
}
參數順序:color image repeat attachment position-x position-y。省略值採用預設。
.bottom-bg {
background-image: url(/images/bg.jpg); /* 設定圖片 */
background-repeat: no-repeat; /* 不重複 */
background-attachment: fixed; /* 固定視窗,不隨內容捲動 */
background-position-x: center; /* 水平置中 */
background-position-y: bottom; /* 垂直靠底 */
/* background-attachment: scroll; */ /* 隨內容捲動(預設) */
}
| 屬性 | 常用值 | 說明 |
|---|---|---|
background-repeat | repeat、repeat-x、repeat-y、no-repeat | 平鋪方式 |
background-attachment | scroll、fixed、local | 捲動行為 |
background-position-x | left、center、right、長度、百分比 | 水平位置 |
background-position-y | top、center、bottom、長度、百分比 | 垂直位置 |
.multi-bg {
background:
url(icon.png) no-repeat left top, /* 第1層:左上圖示 */
url(pattern.png) repeat center center, /* 第2層:中間紋理 */
url(bg.jpg) no-repeat center bottom; /* 第3層:底部大圖 */
background-color: #f0f0f0; /* 兜底色 */
}
多背景按書寫順序疊加,第一層最上層。
.responsive-bg {
background: url(bg.jpg) no-repeat center bottom;
background-size: cover; /* 覆蓋容器,可能裁切 */
/* background-size: contain; */ /* 完整顯示,可能留白 */
/* background-size: 100% auto; */ /* 寬度滿容器,高度自適應 */
min-height: 300px; /* 確保有空間顯示 */
}
背景圖片底部對齊核心在於 background-position-y: bottom(或縮寫 center bottom)。搭配 background-size: cover 與 min-height,即可實現跨裝置自適應的底部背景效果。