Sometimes, we want to fill a div with an image while keeping it proportional with CSS.
In this article, we’ll look at how to fill a div with an image while keeping it proportional with CSS.
How to fill a div with an image while keeping it proportional with CSS?
To fill a div with an image while keeping it proportional with CSS, we use flexbox.
Forr instance, we write
<div class="fill">
<img src="https://picsum.photos/id/237/320/240" alt="" />
</div>
to add a div with an image inside it.
Then we write
.fill {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.fill img {
flex-shrink: 0;
min-width: 100%;
min-height: 100%;
}
to make the div a flex container with display: flex;
.
Then we center the contents horizontally and vertically with justify-content: center;
and align-items: center;
Conclusion
To fill a div with an image while keeping it proportional with CSS, we use flexbox.