每個元素擁有前景層(內容、邊框)與背景層。背景層由下而上疊加:背景顏色(最底) → 多張背景圖片(按聲明順序,第一張最上)。
| 屬性 | 功能 | 常用值 |
|---|---|---|
background-color | 背景顏色 | #fff, rgb(0 0 0 / 0.5), transparent |
background-image | 背景圖片/漸層 | url(...), linear-gradient(...), none |
background-repeat | 平鋪方式 | repeat, repeat-x, repeat-y, no-repeat, space, round |
background-position | 定位起點 | center, top right, 50% 50%, 10px 20px |
background-size | 圖片尺寸 | cover, contain, 100px 50px, 50% |
background-attachment | 滾動行為 | scroll (預設), fixed, local |
background-clip | 繪製裁切區 | border-box, padding-box, content-box, text |
background-origin | 定位基準區 | padding-box (預設), border-box, content-box |
background | 簡寫屬性 | 見下表 |
background: [color] [image] [repeat] [attachment] [position] [/ size] [origin] [clip];
size 必須緊跟 position 並用 / 分隔。origin 與 clip 同值時只寫一次;不同值時第一個為 origin、第二個為 clip。/* 單層 */
background: #f5f5f5 url(noise.png) repeat;
/* 多層:第一層最上 */
background:
url(logo.png) no-repeat center / 100px, /* 層 1 */
linear-gradient(45deg, #fff, #f0f0f0), /* 層 2 */
#fff; /* 底色 */
/* 文字裁切漸層 */
background: linear-gradient(90deg, #f00, #0f0);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
top/center/bottom + left/center/right。50% 50% 將圖片該百分比點對齊容器該百分比點(中心對齊)。20px 30px 將圖片左上角定位在容器左上角偏移處。right 20px bottom 10px 從右/下邊界偏移。top 10px right 20px 明確指定邊界與偏移。| 關鍵字 | 行為 | 保持比例 |
|---|---|---|
cover | 填滿容器,可能裁切 | 是 |
contain | 完整顯示,可能留白 | 是 |
auto | 原始尺寸 | 是 |
100% 100% | 拉伸填滿 | 否(變形) |
.hero {
background:
/* 裝飾層:右上角幾何圖形 */
url(shapes.svg) no-repeat right top / 300px,
/* 內容層:主視覺 */
url(hero.jpg) no-repeat center / cover,
/* 氛圍層:淡漸層 */
linear-gradient(135deg, rgba(255,255,255,0.2), transparent),
/* 底色 */
#1a1a2e;
}
linear-gradient(方向, 色標1, 色標2, ...)
/* 方向 */
to right / 90deg
to bottom right
45deg
/* 色標位置控制 */
linear-gradient(red 0%, orange 30%, yellow 70%, green 100%)
linear-gradient(red, orange 50%, yellow) /* 自動均分 */
radial-gradient(形狀 大小 at 位置, 色標...)
/* 形狀 */ circle | ellipse
/* 大小 */ closest-side | farthest-corner | closest-corner | farthest-side | 明確尺寸
/* 位置 */ center | top left | 50% 50%
radial-gradient(circle farthest-corner at 20% 30%, #f00, #00f)
repeating-linear-gradient(45deg, #fff 0, #fff 10px, #eee 10px, #eee 20px)
/* 斜紋條紋 */
現代瀏覽器無需前綴。歷史專案若需支援 IE11/舊版 Edge,可用 Autoprefixer 自動處理:
-webkit-linear-gradient(...)
-moz-linear-gradient(...)
-ms-linear-gradient(...)
-o-linear-gradient(...)
background-attachment: fixed 在移動端可能導致重繪效能問題,謹慎使用或用 transform: translateZ(0) 強制合成層。CSS 背景系統從單一顏色演進為強大的多層合成引擎:圖片、漸層、尺寸控制、定位邏輯、裁切區域、捲動行為全可精細控制。掌握簡寫順序、多層疊加順序、漸層語法、現代邏輯屬性,能用純 CSS 實現過去需多張圖片、複雜 JS 才能達到的視覺效果。