← 返回完整题库
CSS困难

怎么实现一个固定宽高比(如16:9)的容器

参考答案

方案一:aspect-ratio(首选)

.box { width: 100%; aspect-ratio: 16 / 9; }

方案二:padding-top 百分比(兼容性最好)

padding 百分比相对父宽度,9/16 = 56.25%

.wrap { position: relative; padding-top: 56.25%; }
.inner { position: absolute; inset: 0; }

方案三:Grid 技巧

.box { display: grid; grid-template-rows: 0; aspect-ratio: 16/9; }

本题来自 计算机知识面试题库,共 921 道题。