如何使用CSS缩放图像以填充div保持宽高比? [英] How to scale an image with css to fill a div keeping aspect ratio?

查看:229
本文介绍了如何使用CSS缩放图像以填充div保持宽高比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 img 填充div,保持宽高比,并根据需要适应宽度或高度的拉伸。

 < div style = width:80px; height:80px> 
< img src = ... />
< / div>

如何实现?如果图像不是二次方的,则必须将其放大,并从上到下或从左到右裁剪,这取决于哪一侧更大。此外,图像之后应居中,以使拐角均等。



我尝试过(但没有效果):

  .thumb {
max-width:100%;
最大高度:100%;
}

如果我添加其他宽度:100%; height:100%; ,图像非常合适,但调整后的尺寸没有保持长宽比

  width:100%;  
身高:100%;
object-fit:封面;
溢出:隐藏;


I'd like to fill a div with an img, keeping aspect ratio and stretching either width or height as much as required to fit in.

<div style="width: 80px; height: 80px">
    <img src="..." />
</div>

How could I achieve it? If the image is not quadratic, it must be "zoomed in" and either be scropped top-bottom or left-right, depending which side is the bigger one. Moreover the image should afterwards be centered, so that the corners get cut equally.

I tried (but no effect):

.thumb {
    max-width:100%;
    max-height:100%;
}

If I add additional width: 100%; height:100%;, the images fit perfectly, but are resized not keeping aspect ratio.

解决方案

the following did the trick:

    width:100%;
    height:100%;
    object-fit: cover;
    overflow: hidden;

这篇关于如何使用CSS缩放图像以填充div保持宽高比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆