htmlcssaspect-ratioobject-fit

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


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

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.


Solution

  • 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>