css 只知道宽或高实现等比
2025-02-16 本文已影响0人
litielongxx

大屏兼容等比时有时会用到该方法适配。
方法一 aspect-ratio
.rectangle {
width: 300px; /* 可以根据需要调整宽度 */
aspect-ratio: 16 / 9; /* 设置宽高比为16:9 */
background-color: lightblue;
}
<div class="rectangle"></div>
方法二 嵌套div通过子元素设置padding-top
.container {
width: 300px; /* 可以根据需要调整宽度 */
position: relative;
}
.rectangle {
width: 100%;
padding-top: 56.25%; /* 16:9 的比例,计算公式:(9/16) * 100% */
background-color: lightblue;
position: relative;
}
<div class="container"> <div class="rectangle"></div> </div>