背景圖片不會撐開容器。只有容器的**內容**或**顯式寬高**才能決定容器大小。
body特殊:瀏覽器默認鋪滿視口,故似乎不需寬高;div等普通元素無內容時高度為 0,背景圖不顯示。
/* 無寬高、無內容 */
.div1 { background: url(img.jpg); }
→ 渲染: 0×0 不可見
/* 有寬高 */
.div2 { background: url(img.jpg); width: 300px; height: 200px; }
→ 渲染: 300×200 顯示背景
/* 有內容 */
.div3 { background: url(img.jpg); }
文字內容撐開高度
→ 渲染: 適應內容大小顯示背景
html, body { height: 100%; } (部分瀏覽器)body 是文檔根容器,默認鋪滿視口body 也有隱式寬高,只是由瀏覽器自動計算
.bg-container {
/* 1. 顯式尺寸 (二選一) */
width: 100%; /* 響應式寬度 */
height: 300px; /* 固定高度 */
/* 或 */
aspect-ratio: 16/9; /* 現代 CSS: 固定寬高比 */
/* 2. 背景圖片核心屬性 */
background-image: url('img.jpg');
background-size: cover; /* 覆蓋容器,保持比例裁剪 */
background-position: center; /* 居中對齊 */
background-repeat: no-repeat; /* 不平鋪 */
background-color: #f0f0f0; /* 兜底色,圖片加載前/失敗時顯示 */
/* 3. 現代簡寫 */
background: url('img.jpg') center/cover no-repeat #f0f0f0;
}
| 場景 | 解決方案 |
|---|---|
| 全屏背景 | html { background: url(...) center/cover no-repeat fixed; } (fixed 視差效果) |
| 響應式卡片 | .card { aspect-ratio: 4/3; background: url(...) center/cover; } |
| 自適應高度 | .box { min-height: 200px; background: ...; } 內容少時保底高度 |
| 多重背景 | background: url(a.png) top left, url(b.png) bottom right; |
| 漸變+圖片 | background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)), url(img.jpg); |
cover:縮放填滿容器,**可能裁剪**,最常用contain:縮放完整顯示,**可能留白**100% 100%:拉伸填滿,**變形**auto:原始尺寸
/* 開發時加紅框可視化容器範圍 */
.bg-container { outline: 2px solid red; }
/* 或開發者工具: Elements → Computed → Box Model 查看實際尺寸 */
background-image **不會** 撐開容器width: 100%; aspect-ratio: 16/9; background: center/cover no-repeat;body 只是瀏覽器幫你算好了尺寸,本質相同