Preserving the aspect ratio while resizing images

When you specify both height and width, the image might lose its aspect ratio. You can preserve the aspect ratio by specifying only width and setting height to auto using CSS property.

img {
  width: 400px,
  height: auto
}

 

This will render a 400px wide image. The height is adjusted accordingly to preserve the aspect ratio of the original image. You can also specify the height attribute and set width as auto, but most layouts are generally width constrained and not height.

 

object-fit:contains

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:contain;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

 

The original aspect ratio of the image is same, but the image is resized so that it is fully visible. We have added 1px border around the image to showcase this.

 

 

object-fit:cover

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:cover;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

The original aspect ratio is preserved but to cover the whole area image is clipped from the left and right side.

 

 

object-fit:fill

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:fill;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>

Image is forced to fit into a 200px wide container with height 300px, the original aspect ratio is not preserved.

 

 

object-fit:cover and object-position:right

<img src="https://ik.imagekit.io/ikmedia/backlit.jpg" 
	 style="object-fit:cover;
     		object-position: right;
            width:200px;
            height:300px;
            border: solid 1px #CCC"/>