Make image fit in a container, without object-fit: contain

2.6k views Asked by At

The following code is a perfect solution to make an image:

  • fit in a given container
  • be centered horizontally and vertically in the container
  • use the maximum possible size
  • without changing the aspect ratio

Perfect, except that the library html2canvas doesn't work with object-fit: contain; (see also Html2canvas Ignores Object fit for image).

Question: how to obtain the same behaviour with standard CSS rules, without the relatively-new object-fit?

.container { width: 200px; height: 200px; background: blue; }
img { height: 100%; width: 100%; object-fit: contain; }
1:
<div class="container"><img src="https://via.placeholder.com/100x50"></div>
2:
<div class="container"><img src="https://via.placeholder.com/50x100"></div>
3:
<div class="container"><img src="https://via.placeholder.com/500x300"></div>
4:
<div class="container"><img src="https://via.placeholder.com/300x500"></div>

I've tried various answers from How do I auto-resize an image to fit a 'div' container? but they don't work in all the 4 cases shown before.

2

There are 2 answers

0
Quasipickle On BEST ANSWER

Use background-image instead

.container { 
  width: 200px; 
  height: 200px;
  background-color:blue;
  background-image:var(--bg-img);
  background-repeat:no-repeat;
  background-size:contain;
  background-position: center center;
  
}
<div class="container" style = "--bg-img:url(https://via.placeholder.com/100x50)"></div>

0
Alvaro Menéndez On

As I said before in the comments maybe not possible without javascript for images smaller than containers but in case you won't find a css solution I have made this easy example:

https://jsfiddle.net/zq7vw2y8/1/

Edit. I have made this other JSFIDDLE with much compact script and no jquery