How to Keep Aspect Ratio of Images in CSS
If you ever wanted to resize an image disproportionately without losing aspect ratio in CSS — these two properties will help you out:
/* Center an image in itself without losing aspect ratio */
object-position: 50% 50%;
object-position. By default,
object-fit takes the value of
fill, which scales the image disproportionately if the container doesn't match the aspect ratio of the image.
object-position on the other hand, sets the position of the image inside the container. To better understand how they work, take a look at
object-fit taking up different values:
The original size of the images is 200x300, but they are set to 200x200 through CSS.
object-fit set to
none on every image, observe how
object-position changes the position of the image inside itself:
The original size of the image is 100x100px, but they are set to 200x200 through CSS.
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews