繁体   English   中英

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

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

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

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

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

一种方法是使用object-fit

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

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

设置以下两个:

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

这样可以保持图像自动调整大小,最大值为200px。

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

正如所指出的那样,你可以使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM