| 屬性 | 說明 | 預設值 |
|---|---|---|
| background-color | 背景色 | transparent |
| background-image | 背景圖片/漸層 | none |
| background-repeat | 平鋪模式 | repeat |
| background-attachment | 捲動/固定 | scroll |
| background-position | 定位位置 | 0% 0% (left top) |
| background-size | 縮放大小 | auto |
| background-origin | 定位基準區域 | padding-box |
| background-clip | 繪製裁切區域 | border-box |
/* 順序:color image repeat attachment position / size */
background: #f5f5f5 url("bg.jpg") no-repeat fixed center top / cover;
/* 等效展開 */
background-color: #f5f5f5;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
background-size: cover;
.hero {
background:
/* 第 1 層:裝飾性幾何圖案 */
url("pattern.svg") repeat center / 200px,
/* 第 2 層:漸層覆蓋 */
linear-gradient(135deg, rgba(102,126,234,.9), rgba(118,75,162,.9)),
/* 第 3 層:大圖底圖 */
url("hero.jpg") no-repeat center / cover;
/* 等效展開寫法(較易維護) */
background-image:
url("pattern.svg"),
linear-gradient(135deg, rgba(102,126,234,.9), rgba(118,75,162,.9)),
url("hero.jpg");
background-repeat: repeat, no-repeat, no-repeat;
background-position: center, center, center;
background-size: 200px, cover, cover;
background-attachment: scroll, fixed, scroll;
}
/* 線性漸層 */
linear-gradient(135deg, #667eea 0%, #764ba2 100%)
linear-gradient(to right, red, blue)
linear-gradient(45deg, red 0%, orange 25%, yellow 50%, green 75%, blue 100%)
/* 徑向漸層 */
radial-gradient(circle at center, #fff, #000)
radial-gradient(ellipse 50% 50% at 50% 50%, #fff, #000)
/* 重複漸層(圖案) */
repeating-linear-gradient(45deg, #fff 0, #fff 10px, #eee 10px, #eee 20px)
repeating-radial-gradient(circle, #fff, #fff 10px, #eee 10px, #eee 20px)
/* 從右邊 20px、底部 30px 定位 */
background-position: right 20px bottom 30px;
/* 從左邊 10%、頂部 2em 定位 */
background-position: left 10% top 2em;
.hero {
min-height: 100vh;
background: url("hero.jpg") no-repeat center / cover;
background-attachment: fixed; /* 桌面視差 */
display: flex; align-items: center; justify-content: center;
}
@media (max-width: 768px) {
.hero { background-attachment: scroll; } /* 移動端關閉 fixed 避免效能/定位問題 */
}
.pattern-dots {
background-color: #f0f4f8;
background-image: radial-gradient(circle, #cbd5e1 1px, transparent 1px);
background-size: 20px 20px;
}
.pattern-stripes {
background: repeating-linear-gradient(
45deg, transparent, transparent 10px,
rgba(0,0,0,.03) 10px, rgba(0,0,0,.03) 20px
);
}
background-size: cover 配合 srcset / image-set() 多解析度<link rel="preload" as="image">loading="lazy"(需 JS 觀察器配合)掌握背景技巧後,建議學習 CSS Border 邊框屬性完整指南,完成盒模型視覺控制。