宽高比与内在尺寸
媒体加载前预留空间以消除布局偏移(CLS)。
响应式设计入门
为什么
未知尺寸图片加载时页面跳 — Core Web Vital CLS 惩罚。aspect-ratio 前置预留盒,布局从首绘稳定。
StatCounter 2024 数据显示 58% 的网络流量来自移动端。CSS 容器查询(2023 基线)和 subgrid(2024 基线)消除了大多数媒体查询 hack,减少 30-50% 的响应式 CSS。
何时使用
任何已知比媒体用 aspect-ratio:头像(1:1)、hero 图(16:9)、卡片(4:3)、故事缩略图(9:16)。变比内容加载时测。
如何做
1. 设 aspect-ratio — 盒上 aspect-ratio: 16 / 9、width: 100%、height: auto
2. 填盒 — img { width: 100%; height: 100%; object-fit: cover; } 填充不变形
3. 预留空间 — 图字节到达前盒有正确高,零 CLS
4. 响应式 — 配 max-width 使盒小视口缩,比保持
5. 变比 — 省 aspect-ratio、仅设宽、让高随图(有 CLS)
6. padding-bottom 技巧(旧)— 16:9 用 56.25% padding;aspect-ratio 替代更简
7. 视频 — 同法;<video> 配 aspect-ratio + object-fit: cover 做海报帧
示例
/* 预留 16:9 盒 — 零 CLS,图填之 */
.hero {
width: 100%;
max-width: 1200px;
aspect-ratio: 16 / 9;
}
.hero img { width: 100%; height: 100%; object-fit: cover; }
/* 头像 — 1:1,圆 */
.avatar { aspect-ratio: 1; width: 48px; border-radius: 50%; object-fit: cover; }
/* 响应式卡片缩略图 — 4:3,随容器缩 */
.thumb { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }
/* 旧 padding-bottom 技巧(仅不支持 aspect-ratio 时) */
.legacy-16-9 { position: relative; padding-bottom: 56.25%; height: 0; }
.legacy-16-9 img { position: absolute; inset: 0; width: 100%; height: 100%; }
常见问题
- ⚠图 width:100% 但无 aspect-ratio — 加载前高 0,页面跳(CLS)
- ⚠忘 object-fit — 图变形填盒而非裁切
- ⚠固定 px 高 + aspect-ratio — 冲突;选一,让另一推导
最佳实践
- ✓始终 aspect-ratio 配 object-fit: cover — 预留空间、填不变形
- ✓设宽、让 aspect-ratio 推导高 — 绝不同时设高和 aspect-ratio
- ✓用 aspect-ratio 而非 padding-bottom 技巧 — 更简、无绝对定位、无 height:0