DEV Community

Shafi
Shafi

Posted on

How to Resize Uneven Sized Images without breaking their Aspect Ratio

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Whoo! Our images kept their aspect ratios this time around!

Top comments (3)

Collapse
 
rvxlab profile image
RVxLab

In addition, for background images you can do the same by using background-size: cover instead.

Collapse
 
ashishk1331 profile image
Ashish Khare😎

How about?
Width:200px;
Height:auto;

Collapse
 
shafiemoji profile image
Shafi • Edited

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