【问题标题】:Is it possible to scale an image proportionally both on width and height based on a fixed container?是否可以根据固定容器在宽度和高度上按比例缩放图像?
【发布时间】:2017-11-29 16:32:20
【问题描述】:

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

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

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

【问题讨论】:

  • 我不确定 200x100 和 100x200 是否适合 200x200 的盒子...
  • @JamesDouglas 是的,他们不会填充容器我想要的是让它们按比例缩放,以便它们适合并且不会变形

标签: html css image-scaling


【解决方案1】:

正如其他人指出的那样,您可以使用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>

【讨论】:

    【解决方案2】:

    一种方法是使用object-fit:

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

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

    【讨论】:

    • 太棒了,我考虑过使用background-size 进行类似的修复,但这需要将图像src 移动到CSS 中,这并不理想。不幸的是,IE 是这里的薄弱环节(尽管 Edge 将在 v16 中支持它):caniuse.com/#search=object-fit
    【解决方案3】:

    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" />

    【讨论】:

      【解决方案4】:

      设置这两个:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-19
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 1970-01-01
        • 2012-03-04
        相关资源
        最近更新 更多