簡體   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