javascripthtmlcssimageobject-fit

How to make the photo fit to its container


here I have a div with a class="container", inside this div there is an img, I want the image to cover all the parent div, whatever size it is, also I want the image to preserve its aspect ratio, and the most important thing is, either width or height should be 100% if the other value (width, height) are bigger.

If the image are 2:1 aspect ratio, the height should be 100% to cover all the div and close all the gaps.

I hope you understand me, thanks

.container{
  width: 250px;
  height: 250px;
  background-color: red;
  overflow: hidden;
}
<div class="container">
  <img src="https://img-19.ccm2.net/WNCe54PoGxObY8PCXUxMGQ0Gwss=/480x270/smart/d8c10e7fd21a485c909a5b4c5d99e611/ccmcms-commentcamarche/20456790.jpg" alt="img">
<div/>


Solution

  • Use CSS object-fit: cover

    // demo showing size adjusting at different sizes
    const container = document.querySelector(".container");
    const range = document.querySelector("input[type='range']");
    
    range.addEventListener("input", () => {
      container.style.width = `${range.value}px`;
    });
    .container {
      width: 250px;
      height: 250px;
      background-color: red;
      overflow: hidden;
    }
    img {
      min-width: 100%;
      object-fit: cover;
    }
    <div class="container">
      <img src="https://img-19.ccm2.net/WNCe54PoGxObY8PCXUxMGQ0Gwss=/480x270/smart/d8c10e7fd21a485c909a5b4c5d99e611/ccmcms-commentcamarche/20456790.jpg" alt="img" />
    </div>
    <label for="range">Width of container</label>
    <input type="range" name="range" min="1" value="250" max="600" />