We often have to work with images that varies in size and aspect ratio. But we have to fit them in a container, and to keep the aesthetic of our design we usually choose to resize all the images into a same size.
But taking the easy way out means we have to deal with this...
img {
height: 200px;
width: 200px;
}
This is how they look 🥴
The images have killed their aspect ratios to fit in the height
and width
and this doesn't really help with the aesthetic.
But did you know that we can fix that by adding just one more line of code in our CSS' img
property?
img {
height: 200px;
width: 200px;
object-fit: cover;
}
Whoo! Our images kept their aspect ratios this time around!
Top comments (3)
In addition, for background images you can do the same by using
background-size: cover
instead.How about?
Width:200px;
Height:auto;
If we use
height: auto;
instead of a fixed height, we'd keep the aspect ratio but all of the images would have different height like so i.imgur.com/hGdhivc.png