| 屬性 | 功能 | 預設值 |
|---|---|---|
background-color | 背景顏色 | transparent |
background-image | 背景圖片 | none |
background-repeat | 圖片重複方式 | repeat |
background-position | 圖片起始位置 | 0% 0% (左上角) |
background-attachment | 圖片是否隨捲軸滾動 | scroll |
background | 簡寫屬性 | 見下 |
background-colorbody { background-color: yellow; }
h1 { background-color: #000; }
background-imagebody { background-image: url('bg.gif'); }
h1 { background-image: none; } /* 明確關閉 */
background-repeatbackground-repeat: repeat; /* 水平垂直皆平鋪 (預設) */
background-repeat: repeat-x; /* 僅水平平鋪 */
background-repeat: repeat-y; /* 僅垂直平鋪 */
background-repeat: no-repeat; /* 不重複,單張顯示 */
background-position/* 關鍵字 */
background-position: left top; /* 左上 */
background-position: center center; /* 正中間 */
background-position: right bottom; /* 右下 */
/* 百分比:相對於 (容器尺寸 - 圖片尺寸) */
background-position: 50% 50%; /* 置中 */
background-position: 100% 0; /* 右上 */
/* 長度值:相對左上角絕對偏移 */
background-position: 100px 50px; /* 右移 100px、下移 50px */
/* 單一值:第二值預設 50% */
background-position: right; /* 等同 right center */
負值會使圖片超出容器邊界。
background-attachmentbackground-attachment: scroll; /* 預設:隨內容滾動 */
background-attachment: fixed; /* 固定於視窗,視差效果基礎 */
background順序建議:color image repeat attachment position,中間以空格分隔。顏色勿放在圖片 URL 之後,否則圖片可能不顯示。
/* 完整範例:綠色背景 + 圖片固定於 (100px, 50px) 不重複 */
body {
background: green url('bg.gif') no-repeat fixed 100px 50px;
}
/* 常用簡寫:置中不重複 */
.container {
background: #f5f5f5 url('pattern.png') no-repeat center center;
}
/* CSS3 多重背景(現代瀏覽器) */
.hero {
background:
url('overlay.png') no-repeat center,
linear-gradient(135deg, #667eea, #764ba2);
}
background: url('hero.jpg') no-repeat center center / cover fixed;(background-size: cover + fixed 視差)background: url('quote.png') no-repeat left 20px top 10px;background: url('sprite.png') no-repeat -10px -50px; 配合 width/height 切圖。background 簡寫會重置未指定的子屬性為預設值,注意覆蓋順序。