背景圖片是視覺設計的核心工具。本文系統梳理 background 相關屬性、合寫語法、多背景應用、響應式圖片與性能優化策略。
| 屬性 | 作用 | 常用值 | 默認值 |
|---|---|---|---|
background-image | 設置背景圖片 | url(), linear-gradient(), none | none |
background-repeat | 平鋪方式 | repeat, no-repeat, repeat-x, repeat-y, space, round | repeat |
background-position | 定位位置 | center, top left, 50% 50%, 10px 20px | 0% 0% |
background-size | 圖片尺寸 | cover, contain, 100% 100%, auto | auto |
background-attachment | 滾動行為 | scroll, fixed, local | scroll |
background-origin | 定位基準區域 | padding-box, border-box, content-box | padding-box |
background-clip | 繪製裁剪區域 | border-box, padding-box, content-box, text | border-box |
background-color | 回退背景色 | 顏色值 | transparent |
/* 完整合寫順序:image position/size repeat attachment origin clip color */
background:
url("hero.jpg") /* image */
center / cover /* position / size */
no-repeat /* repeat */
fixed /* attachment */
padding-box /* origin */
border-box /* clip */
#f0f0f0; /* color (回退) */
/* 實際常用簡化版 */
.card {
background: url("icon.png") left center no-repeat #fff;
}
.hero {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.multi-bg {
/* 先寫的在上層,後寫的在下層 */
background:
url("pattern.png") repeat, /* 第1層:紋理 */
url("logo.png") 20px 20px no-repeat, /* 第2層:Logo */
linear-gradient(45deg, #1a2a6c, #b21f1f, #fdbb2d); /* 第3層:漸變底色 */
background-color: #1a2a6c; /* 最後兜底色 */
}
.hero {
background: url("hero-mobile.jpg") center/cover no-repeat;
min-height: 300px;
}
@media (min-width: 768px) {
.hero {
background-image: url("hero-tablet.jpg");
min-height: 450px;
}
}
@media (min-width: 1200px) {
.hero {
background-image: url("hero-desktop.jpg");
min-height: 600px;
}
}
/* 現代寫法:image-set() (WebKit/Blink) 或 picture + img */
.hero-modern {
background-image: image-set(
url("hero-1x.jpg") 1x,
url("hero-2x.jpg") 2x,
url("hero-3x.jpg") 3x
);
}
.icon {
display: inline-block;
background: url("sprite.png") no-repeat;
background-size: 200px auto; /* sprite 總寬 */
}
.icon-user { width: 24px; height: 24px; background-position: 0 0; }
.icon-search { width: 24px; height: 24px; background-position: -24px 0; }
.icon-cart { width: 24px; height: 24px; background-position: -48px 0; }
.rounded-card {
border-radius: 16px;
background: url("cover.jpg") center/cover no-repeat;
/* 關鍵:背景裁剪到內邊距區域,配合 border-radius 形成圓角 */
background-clip: padding-box;
}
.text-gradient {
background: linear-gradient(90deg, #ff6b6b, #feca57, #48dbfb);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 3rem;
font-weight: bold;
}
<picture> 回退 JPEG);圖標/幾何圖形用 SVG;簡單幾何紋理用 CSS 漸變替代圖片loading="lazy" (需 <img>) 或 IntersectionObserver 手動觸發Cache-Control: max-age=31536000, immutable),文件名含 hash警告:彩色/複雜背景圖上直接疊加文字嚴重影響可讀性。
background: rgba(0,0,0,0.5) url(...) 或偽元素遮罩