Appearance
保持元素宽高比(至少3种)
1. 使用 padding-top 或 padding-bottom(兼容所有浏览器)
css
.aspect-ratio {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 宽高比 */
/* 16:9 → padding-top: 56.25% */
/* 4:3 → padding-top: 75% */
/* 1:1 → padding-top: 100% */
}
.aspect-ratio-content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 防止内容溢出 */
overflow: hidden;
}2. 使用 aspect-ratio 属性(兼容现代浏览器!)
css
.aspect-ratio {
width: 100%;
aspect-ratio: 16 / 9;
/* 内容样式 */
}3. 使用 vw 和 vh 单位(兼容现代浏览器!)
css
.aspect-ratio {
width: 100vw;
height: 56.25vw; /* 16:9 宽高比 */
/* 内容样式 */
}4. 使用 SVG 占位符
css
.aspect-ratio {
position: relative;
width: 100%;
}
.aspect-ratio svg {
width: 100%;
height: auto;
display: block;
}
.aspect-ratio-content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 内容样式 */
}html
<div class="aspect-ratio">
<svg viewBox="0 0 16 9" preserveAspectRatio="none">
<rect width="16" height="9" fill="transparent" />
</svg>
<div class="aspect-ratio-content">
<!-- 内容 -->
</div>
</div>