How to auto resize an image to fit within a DIV without stretching?

If you are developing a Responsive Webpage or a Fluid Web page, you would have definitely come across scenarios where you wanted to fit in a large image within a smaller DIV without distorting it or breaking the aspect ratio. Well, this can be done easily using the max-width property.

Let’s assume that I have an image which is 768px wide and I want to fit it within a DIV whose width is 320px. Let’s call the DIV as “figure-container” . To fit the image within the “figure-container” DIV, I should be using the max-width property to the image. Hence my CSS might look similar to the following :

.figure-container img{ 
  max-width: 100%; 
  display: block; 
  height: auto 
}

This would ensure that the image’s width does not exceed 100% of the DIV’s width. Which means my image which was of 768px would now fit within the 320px DIV while maintaining the aspect-ratio too. However, please remember that depending on your scenario, you might have to use the display property too. You may set the display to block or inline-block.

The other way to do this is by using the object-fit property on the image.

How to fit an image in div using CSS object-fit?

You can also use the object-fit property of CSS3 to fit your image within the parent DIV. All you have to do is to add the object-fit property to the image. The Object-fit property has 4 values, they are :

1. fill – This would stretch the image to fit the content box.
2. contain – This would scale the image up or down to fill the content box while maintaining the aspect-ratio.
3. cover – This would fill the content box with the image while maintaining the aspect-ratio, but might crop the image in this process.
4. none – The image would retain its original dimensions.
5. scale-down – The image would be sized like using the none or contain property while generating the smallest concrete object size.

.figure-container img{
  width: 100%;
  height:100%;
  object-fit:contain; /* This can be one of the 5 values from above */
}

When you use the object-fit property to fit the image within the DIV, you would have to use it along with one of the fill, cover or contain value. However, please note that the support for object-fit across devices and browsers is still evolving so please do check for the browser support before you use it. There are a couple of PolyFills available for object-fit, however please try those out before you actually go ahead and use it on a live site.