Sometimes, we want to maintain the image aspect ratio when changing height with CSS.
In this article, we’ll look at how to maintain the image aspect ratio when changing height with CSS.
How to maintain the image aspect ratio when changing height with CSS?
To maintain the image aspect ratio when changing height with CSS, we use the object-fit
property.
For instance, we write
<div class="slider">
<img src="https://picsum.photos/300/300" alt="image" />
<img src="https://picsum.photos/300/300" alt="image" />
<img src="https://picsum.photos/300/300" alt="image" />
<img src="https://picsum.photos/300/300" alt="image" />
</div>
to add the img elements
Then we write
.slider {
display: flex;
}
.slider img {
margin: 0 5px;
object-fit: contain;
}
to add object-fit: contain;
to make the images keep their aspect ratio.
Conclusion
To maintain the image aspect ratio when changing height with CSS, we use the object-fit
property.