background 是 CSS 中功能最豐富的簡寫屬性之一,能在單一宣告中設定顏色、圖片、定位、尺寸、重複、繪製區域、捲動行為等八大子屬性。本文逐項拆解語法、預設值、實務技巧,助你寫出精簡且可維護的背景樣式。
| 子屬性 | 功能 | 預設值 | 常用值範例 |
|---|---|---|---|
background-color | 背景顏色 | transparent | #fff, rgba(0,0,0,0.5), hsl(200,50%,80%) |
background-image | 背景圖片(可多層,逗號分隔) | none | url(bg.png), linear-gradient(...), none |
background-position | 圖片初始位置 | 0% 0% (left top) | center center, right bottom, 50px 100px |
background-size | 圖片尺寸 | auto | cover, contain, 100% 100%, 200px auto |
background-repeat | 重複方式 | repeat | no-repeat, repeat-x, repeat-y, space, round |
background-origin | 定位基準區域 | padding-box | border-box, padding-box, content-box |
background-clip | 繪製裁切區域 | border-box | border-box, padding-box, content-box, text(文字裁切) |
background-attachment | 捲動行為 | scroll | fixed(視差效果), local(隨元素捲動) |
標準順序(順序可互換,但 background-size 必須緊跟在 background-position 後並用 / 分隔):
background:
[background-color]
[background-image]
[background-position] / [background-size]
[background-repeat]
[background-attachment]
[background-origin]
[background-clip];
/* 1. 基礎:純色 + 置中不重複圖片 */
.bg-basic {
background: #f5f5f5 url(logo.png) no-repeat center center;
}
/* 2. 響應式全螢幕背景 */
.bg-cover {
background: url(hero.jpg) no-repeat center center / cover;
background-attachment: fixed; /* 視差滾動 */
}
/* 3. 多層背景:漸變疊加圖案 */
.bg-multi {
background:
linear-gradient(135deg, rgba(0,0,0,0.6), transparent), /* 頂層 */
url(pattern.png) repeat 0 0, /* 中層 */
#333; /* 底層色 */
}
/* 4. 文字裁切背景(漸變文字) */
.text-gradient {
background: linear-gradient(90deg, #f00, #0f0, #00f);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
}
/* 5. 內容區域繪製背景(不延伸到 border) */
.bg-content-box {
border: 10px dashed #ccc;
padding: 20px;
background: url(bg.png) no-repeat center / cover;
background-origin: content-box; /* 定位基準 */
background-clip: content-box; /* 裁切範圍 */
}
background-color 是最後防線,習慣寫在最後或最前。/ 分隔,如 center / cover,否則會被解析為 position 的兩個值。color: transparent,且需加 -webkit- 前綴支援 Safari/舊版 Chrome。background-attachment: fixed 在移動端可能造成卡頓,建議用 transform: translateZ(0) 開啟 GPU 加速或改用 JS 視差。結語:熟練掌握 background 簡寫,能大幅減少 CSS 行數,並集中管理視覺樣式。建議在專案中建立 .bg-* 工具類別,封裝常用背景模式,提升團隊協作一致性。