Skip to main content

长宽比

padding-bottom/top

垂直方向上的内外边距使用百分比做单位时,是基于包含块的宽度来计算的。

<div class="parent">
<div class="child" />
</div>
.parent {
width: 40vw;
}
.child {
width: 100%;
height: 0;
padding: 0;
padding-bottom: 75%;
margin: 50px;
background-color: lightsalmon;
}

aspect-ratio

通过 padding-bottom 来 hack 的方式也很不直观,并且需要元素的嵌套。

/* 高度随动 */
.box1 {
width: 100%;
height: auto;
aspect-ratio: 16/9;
}

/* 宽度随动 */
.box2 {
height: 100%;
width: auto;
aspect-ratio: 16/9;
}