是否可以基于固定容器在宽度和高度上按比例缩放图像? [英] Is it possible to scale an image proportionally both on width and height based on a fixed container?

查看:21
本文介绍了是否可以基于固定容器在宽度和高度上按比例缩放图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 400x200 的图像和另一个 200x400 的图像,我希望它们适合一个 200x200 的盒子,所以第一个应该缩放到 200x100,第二个应该缩放到 100x200

Suppose we have an image that is 400x200 and another that is 200x400 and I want them to fit in a 200x200 box so the first should be scaled to 200x100 and the second to 100x200

我们不会提前知道图片的尺寸.

We won't know the dimensions of the images in advance.

[edit] 很多好的答案,谢谢大家!

[edit] Plenty of good answers, thank you all!

推荐答案

一种方法是使用 object-fit:

One way is to use object-fit:

img {
  object-fit: contain;
  width: 200px;
  height: 200px;
}

JSFiddle 演示:https://jsfiddle.net/t75cxqt0/2/

这篇关于是否可以基于固定容器在宽度和高度上按比例缩放图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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