p { background-color: gray; padding: 20px; }
em、a)transparent(透明),不可繼承body { background-image: url(/i/bg.gif); }
p.flower { background-image: url(/i/flower.gif); }
a.radio { background-image: url(/i/radio.gif); }
none,不可繼承textarea、select)也支持,但瀏覽器實現不一body { background-repeat: repeat-y; }
| 值 | 效果 |
|---|---|
repeat | 水平垂直雙向平鋪(默認) |
repeat-x | 僅水平平鋪 |
repeat-y | 僅垂直平鋪 |
no-repeat | 不平鋪,單張顯示 |
圖片從元素 **左上角(padding 內邊距起始處)** 開始平鋪。
body { background-position: center; }
| 單一關鍵字 | 等效雙關鍵字 |
|---|---|
| center | center center |
| top | top center / center top |
| bottom | bottom center / center bottom |
| right | right center / center right |
| left | left center / center left |
單關鍵字時另一維度默認 center。順序不限,但不超過兩個(一橫一縱)。
body { background-position: 50% 50%; } /* 居中 */
body { background-position: 66% 33%; } /* 水平 2/3、垂直 1/3 */
核心規則:百分比**同時作用於元素與圖片**。即圖片的 50% 50% 點(中心)與元素的 50% 50% 點對齊。
0% 0% = 左上角對齊;100% 100% = 右下角對齊。
單值時垂直默認 50%。
body { background-position: 50px 100px; }
偏移基準:元素 padding 左上角 → 圖片左上角。與百分比不同,**不涉及圖片自身尺寸計算**。
body { background-attachment: fixed; }
scroll(默認):隨文檔滾動fixed:相對視口固定,視差滾動效果基石body {
background: #fff url(/i/bg.jpg) no-repeat fixed center / cover;
/* color image repeat attachment position/size */
}
現代 CSS 支持 background-size(cover/contain/長度值)實現響應式背景圖縮放。