background 是 CSS 功能最豐富的屬性群。本文系統整理背景圖片的所有控制屬性,提供可直接套用的完整範例與最佳實踐。
.box {
width: 200px; height: 100px;
border: 1px solid red; color: #fff;
/* 核心屬性 */
background-image: url("photo.gif"); /* 圖片路徑,建議加引號 */
background-repeat: repeat-x; /* 水平平鋪 */
background-position: left top; /* 起始位置 */
background-attachment: scroll; /* scroll 隨內容捲動 | fixed 固定視窗 */
background-size: auto; /* auto 原尺寸 | cover 覆蓋 | contain 完整顯示 | 100% 100% 拉伸 */
background-color: #f0f0f0; /* 兜底色,圖片透明/未載入時顯示 */
/* 縮寫(順序:color image repeat attachment position/size) */
background: #f0f0f0 url("photo.gif") repeat-x scroll left top / auto;
}
| 屬性 | 值範例 | 說明 |
|---|---|---|
background-image | url("img.png"), linear-gradient(...), none | 多背景用逗號分隔,第一層最上 |
background-repeat | repeat, repeat-x, repeat-y, no-repeat, space, round | space 等間距平鋪, round 縮放填滿 |
background-position | left top, center, right bottom, 10px 20px, 50% 50% | 關鍵字/長度/百分比,可單寫 X/Y |
background-attachment | scroll, fixed, local | local 隨元素內容捲動 |
background-size | auto, cover, contain, 100% 100%, 200px 100px | 可用 背景尺寸/背景位置 寫在縮寫中 |
background-origin | padding-box, border-box, content-box | 定位基準區域,預設 padding-box |
background-clip | border-box, padding-box, content-box, text | 繪製裁切區域,text 可做文字遮罩 |
.hero {
min-height: 100vh;
background: url("hero.jpg") no-repeat center center / cover;
/* 等同 background-size: cover; background-position: center; */
}
.parallax {
height: 500px;
background: url("bg.jpg") no-repeat center center / cover fixed;
/* fixed 產生視差感,移動端可能有效能/顯示問題,建議媒體查詢關閉 */
}
@media (max-width: 768px) {
.parallax { background-attachment: scroll; }
}
.lazy-img {
background: url("blur-placeholder.jpg") no-repeat center / cover;
transition: background 0.3s;
}
.lazy-img.loaded { background-image: url("full-res.jpg"); }
.text-mask {
background: url("texture.jpg") no-repeat center / cover;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
font-size: 4rem; font-weight: bold;
}
url() 路徑相對於 CSS 檔案位置,非 HTML 頁面。/images/xxx.jpg 避免目錄層級變動失效。url() 可不加引號,但含空格/特殊字元時必須加引號。background-size: cover 避免圖片過大浪費頻寬。<link rel="preload" as="image" href="hero.jpg">。background-attachment: fixed,移動端謹慎使用(重繪成本高)。背景圖片屬性看似繁多,掌握 image → repeat → position → attachment → size → origin → clip 七大維度,即可精準控制任何背景表現。現代開發建議:縮寫用於簡單場景,複雜多背景用拆解寫法,配合 CSS 變數管理主題路徑。