Skip to content Skip to sidebar Skip to footer

Is It Possible To Scale An Image Proportionally Both On Width And Height Based On A Fixed Container?

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 w

Solution 1:

One way is to use object-fit:

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

JSFiddle Demo: https://jsfiddle.net/t75cxqt0/2/

Solution 2:

Set both of these:

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

That will keep allow the images to resize automatically to a maximum of 200px on either side.

Solution 3:

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

Solution 4:

As pointed out elsewere, you could use max-height and max-width, which is good. But I'd like to take it a step further, and make it so that it doesn't matter what the container size is. Use a percentage value instead of 200px:

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

Here is an example:

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

To prove this works, I have written some code (unnecessary for your actual code). You just need to enter the desired width + height for the container, and you can see the effect!

functionsize() {
  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%;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><buttonstyle="float: right;"onclick="size()">Choose size values</button><divclass="container"><imgsrc="http://www.piprd.com/images/400X200.gif"></div><divclass="container"><imgsrc="https://fakeimg.pl/200x400/"></div>

Post a Comment for "Is It Possible To Scale An Image Proportionally Both On Width And Height Based On A Fixed Container?"