Fit image to div without stretching | CSS background-size Property

You want to Fit image to div and want to set it a specific width and height (in pixels) on the HTML web page. But the problem is Fill div with an image without stretching it.

If you set width and height using CSS (width:250px; height:300px), the image will be stretched, and It may be ugly.

Let’s see the images and Fit image to div

Original Image: 1080 x 1920

Fit image to div without stretching

Stretched Image: width: 250px; height: 300px;

Stretched Image

Filled Image: width: 250px; height: 300px;

Filled Image

How to fit image without stretching and maintain aspect ratio?

Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property.

  • contain will give you a scaled-down image.
  • cover will give you a scaled-up image

Example:

Output:

image aspect-ratio

Q: How do you stretch an image to fill a <div> while keeping the image’s aspect-ratio?

Answer: Use background-size: contain, the image is resized to fit the height but the width isn’t entirely filled.

OR

You could just state the width of the image and have the height auto

Do comment if you have any doubts and suggestions on this tutorial.

Note: The All Examples code HTML Fit image to div is tested on the Safari browser (Version 12.0.2).
OS: macOS 10.14 Catalina
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.