是否可以基于固定容器在宽度和高度上按比例缩放图像?

Is it possible to scale an image proportionally both on width and height based on a fixed container?

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

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

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

设置这两个:

max-width: 200px;
max-height: 200px;

这将允许图像自动调整大小,每边最大为 200 像素。

img {
  max-width: 200px;
  max-height: 200px;
  
  /* just for demo purposes*/
  margin: 1em;
}
<img src="https://dummyimage.com/400x200/000/fff" />
<img src="https://dummyimage.com/200x400/000/fff" />

一种方法是使用 object-fit:

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

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

正如其他地方指出的,您可以使用 max-heightmax-width,这很好。但我想更进一步,让容器大小无关紧要。 使用百分比值代替 200px:

img {
  max-width: 100%;
  max-height: 100%;
}

这是一个例子:

.container {
  border: 5px solid blue;
  width: 200px;
  height: 200px;
}
img {
  max-width: 100%;
  max-height: 100%;
}
<div class="container">
  <img src="http://www.piprd.com/images/400X200.gif">
</div>
<div class="container">
  <img src="https://fakeimg.pl/200x400/">
</div>

为了证明这是可行的,我编写了一些代码(您的实际代码不需要)。你只需要输入你想要的容器宽+高,就可以看到效果了!

function size() {
  var width = prompt("Please enter width for container", "200px");
  var height = prompt("Please enter height for container", "200px");
  if (width != null) {
    $('.container').css('width', width);
  }
  if (height != null) {
    $('.container').css('height', height);
  }
}
.container {
  border: 5px solid blue;
  width: 200px;
  height: 200px;
}

img {
  max-width: 100%;
  max-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button style="float: right;" onclick="size()">Choose size values</button>
<div class="container">
  <img src="http://www.piprd.com/images/400X200.gif">
</div>
<div class="container">
  <img src="https://fakeimg.pl/200x400/">
</div>