You want to Fit the image to div and want to set it a specific width and height (in pixels) on the HTML web page. But the problem is to 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
Stretched Image: width: 250px; height: 300px;
Filled Image: width: 250px; height: 300px;
object-fit: fill
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:
<!DOCTYPE html>
<html>
<style type="text/css">
.container {
width: 250px;
height: 300px;
background-image: url(ca.jpg);
background-size: contain;
background-repeat: no-repeat;
background-position: 50% 50%;
}
</style>
<body>
<div class="container"></div>
</body>
</html>
Output:
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
.div img {
width: 310px;
height: auto;
}
<div class="div">
<img src="#" title="#">
</div>
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