background-size: <bg-size>#;
<bg-size> = [ <length-percentage> | auto ]{1,2} | cover | contain
| 值 | 行為 | 保持比例 | 覆蓋區域 | 典型場景 |
|---|---|---|---|---|
auto (默認) | 原圖尺寸 | ✅ | 可能留白/溢出 | 圖標、精確像素圖 |
contain | 等比縮放,**完整顯示** | ✅ | 留白(letterbox) | Logo、產品圖、不能裁剪場景 |
cover | 等比縮放,**填滿容器**(可能裁剪) | ✅ | 無留白 | Hero Banner、全屏背景、卡片封面 |
<length> | 固定寬高(如 200px 100px) | ❌ 強制拉伸 | 精確控制 | 固定尺寸裝飾圖 |
<percentage> | 相對容器百分比 | ❌ 非 1:1 時變形 | 響應式佔比 | 流式佈局背景 |
/* 一值:寬度,高度自動計算保持比例 */
background-size: 200px; /* 寬 200px,高 auto */
background-size: 50%; /* 寬 50%,高 auto */
/* 二值:寬度 高度 */
background-size: 200px 100px; /* 固定尺寸,可能變形 */
background-size: 50% 100%; /* 寬半容器、高滿容器 */
background-size: auto 100px; /* 高固定 100px,寬等比 */
background-size: 100px auto; /* 寬固定 100px,高等比 */
.hero {
background-image:
url(pattern.png), /* 第 1 層:頂層裝飾 */
url(hero.jpg); /* 第 2 層:主背景 */
background-size:
200px 200px, /* pattern 固定 200px 方塊平鋪 */
cover; /* hero 圖覆蓋填滿 */
background-repeat:
repeat, /* pattern 平鋪 */
no-repeat; /* hero 不重複 */
background-position:
center, /* pattern 居中 */
center center; /* hero 居中 */
}
層級順序:第一層最頂層,最後一層最底層。屬性值列表一一對應,單值自動擴展到所有層。
.hero {
min-height: 100vh;
background: url(hero.jpg) center / cover no-repeat;
/* 關鍵內容區域避免被裁剪 */
background-position: center 30%; /* 焦點在上 30% */
}
@media (max-width: 768px) {
.hero { background-position: center top; } /* 移動端優先顯示頂部 */
}
.card-thumb {
aspect-ratio: 16 / 9; /* 現代:預留比例空間 */
background: var(--img-url) center / cover no-repeat;
/* 兼容舊瀏覽器:padding-top hack */
/* padding-top: 56.25%; height: 0; background: ...; */
}
.icon-sprite {
width: 24px; height: 24px;
background: url(sprite.svg) no-repeat;
background-size: auto 24px; /* 高固定 24px,寬等比 */
}
.icon-home { background-position: 0 0; }
.icon-user { background-position: -24px 0; }
.parallax {
height: 100vh;
background: url(deep.jpg) center / cover no-repeat fixed;
/* 移動端 fixed 失效,需 JS 方案或 media query 降級 */
}
@media (max-width: 768px) {
.parallax { background-attachment: scroll; }
}
| 現象 | 原因 | 修復 |
|---|---|---|
| 圖片模糊 | 容器大於原圖,cover 放大 | 提供高分辨率源圖 / 使用 SVG / 限制容器最大尺寸 |
| 百分比基準困惑 | 相對「定位區域」(含 padding) | 配合 background-origin: content-box/padding-box/border-box |
| 多背景層級錯亂 | 屬性值列表長度不一 | 顯式寫全每層值,或用 background 簡寫 |
| 移動端 fixed 失效 | iOS/Android 視口處理差異 | 媒體查詢降級 scroll 或 JS 視差 |
:root {
--hero-img: url('hero.jpg');
--hero-img-webp: url('hero.webp');
--hero-img-avif: url('hero.avif');
}
.hero {
background-image: var(--hero-img);
background-size: cover;
}
/* JS 檢測支持度動態注入更優格式 */
background-size 是背景圖靈活佈局的核心屬性。掌握 cover/contain/百分比/多層獨立控制,配合 aspect-ratio、container queries,能以最小代碼實現最豐富的視覺效果。