-1

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/>
  • 2
    Does this answer your question? [How do I auto-resize an image to fit a 'div' container?](https://stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container) – Art Aug 30 '21 at 14:55
  • try object-fit: contain, it will fit based on the aspect ratio – Maharajan Aug 30 '21 at 15:06

3 Answers3

0

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" />
Jacob
  • 1,577
  • 8
  • 24
0

The object-fit property might come in handy here.

Add a class to your image, say .image. Then provide the following styles:

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

That should do the trick. Check the other values for object-fit to see how else you might style images like this in the future.

Feel free to play around with a demo here.

McCambley
  • 1
  • 1
0

You can also use the image as a background-image to your container with a background-size: cover.

.container{
  width: 250px;
  height: 250px;
  background-image: url("https://img-19.ccm2.net/WNCe54PoGxObY8PCXUxMGQ0Gwss=/480x270/smart/d8c10e7fd21a485c909a5b4c5d99e611/ccmcms-commentcamarche/20456790.jpg");
  background-size: cover;
}