css实现固定的图片的纵横比例

395 阅读1分钟

例如需要固定的比例为16:9,通过百分比设置宽度,计算出高度的百分比数值,设置内边距为高度的数值,最后用绝对定位把图片百分百填充到我们设置的区域里面。

以下为html代码

<div class="teaching-video-container">
    <div class="teaching-video-card">
        <img src="images/teaching-video-background.jpg" alt="">
    </div>
</div>

以下为css代码

.teaching-video-card{
    width: 23.5%;
    position: relative;
    padding-bottom: 13.22%;
    margin-bottom: 35px;
}

.teaching-video-card img{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

最终效果图:呈现的比例约等于16:9

image.png