Sometimes, we want to stretch an image to fill a div while keeping the image’s aspect ratio with CSS.
In this article, we’ll look at how to stretch an image to fill a div while keeping the image’s aspect ratio with CSS.
How to stretch an image to fill a div while keeping the image’s aspect ratio with CSS?
To stretch an image to fill a div while keeping the image’s aspect ratio with CSS, we set the image as the div’s background.
For instance, we write
<div class="fill"></div>
to add a div.
Then we write
.fill {
overflow: hidden;
background-size: cover;
background-position: center;
background-image: url("path/to/image.jpg");
}
to set image.jpg as the background of the div.
We add background-size: cover;
to make the background image fill the div.
And we add background-position: center;
to center the background image in the div.
Conclusion
To stretch an image to fill a div while keeping the image’s aspect ratio with CSS, we set the image as the div’s background.