Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 won't know the dimensions of the images in advance.

[edit] Plenty of good answers, thank you all!

like image 494
Samus_ Avatar asked Jan 01 '26 10:01

Samus_


1 Answers

One way is to use object-fit:

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

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

like image 150
Miguel Mota Avatar answered Jan 03 '26 01:01

Miguel Mota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!