css自适应正方形方案
1. aspect-ratio(现代方案,推荐)
.square {
width: 50%;
aspect-ratio: 1 / 1;
background: pink;
}
aspect-ratio: 1/1 直接锁定宽高比,简洁现代。
2. padding-bottom 百分比(经典方案)
.square {
width: 50%;
height: 0;
padding-bottom: 50%; /* padding 百分比相对父元素宽度计算 */
background: pink;
}
原理:padding 的百分比是相对父元素宽度计算的,所以宽高会保持一致。
如果内部需要放内容:
.square {
width: 50%;
height: 0;
padding-bottom: 50%;
position: relative;
background: pink;
}
.square .content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
3. vw 单位
.square {
width: 50vw;
height: 50vw; /* 和 width 用同一个 vw 值 */
background: pink;
}
适合相对视口宽度的场景。
方案对比
| 方案 | 推荐度 | 说明 |
|---|---|---|
aspect-ratio |
✅ 首选 | 现代浏览器均支持,最简洁 |
padding-bottom |
✅ 可用 | 兼容性最好,老项目适用 |
vw |
场景限定 | 只适合相对视口的场景 |
首选 aspect-ratio,兼容老浏览器用 padding-bottom 方案。
