Sometimes, we want to scale an image to fit a bounding box with CSS.
In this article, we’ll look at how to scale an image to fit a bounding box with CSS.
How to scale an image to fit a bounding box with CSS?
To scale an image to fit a bounding box with CSS, we set a few background properties.
For instance, we write
<div class="bounding-box"></div>
to add a div.
Then we write
.bounding-box {
background-image: url(https://picsum.photos/200/300);
background-repeat: no-repeat;
background-size: contain;
}
to set the background image’s URL with background-image: url(https://picsum.photos/200/300);
.
We stop the background image from tiling with background-repeat: no-repeat;
.
And we keep the background image in the div with background-size: contain;
.
Conclusion
To scale an image to fit a bounding box with CSS, we set a few background properties.