背景屬性是頁面視覺基調的關鍵。本文系統講解 background-color、background-image、background-repeat、background-position、background-attachment 及綜合簡寫,附最佳實踐與陷阱提醒。
background-colorbody { background-color: yellow; }
h1 { background-color: #000; } /* 十六進位 */
.section { background-color: rgb(255,255,255); } /* RGB */
預設 transparent。建議同時設定背景色作為圖片載入失敗時的保底。
background-imagebody { background-image: url('../images/bg.png'); }
h1 { background-image: none; } /* 明確關閉繼承圖片 */
預設 none。路徑相對 CSS 檔案位置。
background-repeat| 值 | 行為 |
|---|---|
repeat | 水平垂直雙向平鋪(預設) |
repeat-x | 僅水平平鋪 |
repeat-y | 僅垂直平鋪 |
no-repeat | 不平鋪,單張顯示 |
space | 平鋪並均勻分佈空白(CSS3) |
round | 平鋪並縮放填滿無縫隙(CSS3) |
background-positionleft/center/right + top/center/bottom(如 center center、right bottom)。50% 50% 為中心,0% 0% 為左上角。100px 10px 相對左上角偏移。50%(垂直置中)。background-attachmentscroll(預設):隨頁面捲動。fixed:固定於視口,視差效果基礎。local:隨元素內容捲動(CSS3)。background(順序不嚴格,建議統一)/* 推薦順序:color image repeat position attachment */
body {
background: #f5f5f5 url('../images/bg.png') no-repeat center top fixed;
}
/* 等效展開 */
background-color: #f5f5f5;
background-image: url('../images/bg.png');
background-repeat: no-repeat;
background-position: center top;
background-attachment: fixed;
關鍵提醒: 背景色必須寫在最前或最後,不可夾在圖片 URL 之後,否則圖片可能不顯示。
.multi-bg {
background:
url('pattern.png') repeat 0 0,
url('hero.jpg') no-repeat center center,
linear-gradient(45deg, #fff, #f0f0f0);
}
逗號分隔,第一層最上層。漸層視為背景圖片一種。
background-attachment: fixed 可能導致捲動卡頓,移動端慎用。image-set()。精通背景屬性組合,能以最少代碼創造豐富視覺層次,並兼顧效能與無障礙。