Signup/Sign In

How to Auto-resize an Image to Fit into a DIV Container using CSS?

Answer: Using width and height property

The image does not fit itself to the parent container. The image may overflow if it is larger than its parent container. It is very easy to auto-size images to fit into a div container.

In this tutorial, we will learn about the CSS properties used to auto-size the image.

Auto-resizing an image

The width and height properties can be used to auto-resize the image so that it fits into the div container. Do not use explicit height and width to the image tag. Rather use max-width: 100% and max-height: 100%.

Example: Auto-resize image using height and width properties

Here in the example, we have taken three different sizes div container and tried to fit the images to the container using max-height and max-width properties.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>

   img {
        max-width: 100%;
        max-height: 100%;
      }
      div {
        border: 2px solid blue;
		
      }
      .small  {
        height: 100%;
        width: 40px;
      }
      .medium  {
        height: 100%;
        width: 80px;
      }
      .large  {
        height: 100%;
        width: 100px;
      }
</style>
</head>
<body>
    <h2> Auto-resize image to fit container</h2>
	<p> Small div block </p>
	<div class="small ">
		<img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1627986342-101156.png" alt="image">
	</div>
	<p> medium div block </p>
	<div class="medium ">
		<img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1627986342-101156.png" alt="image">
	</div>
	<p> large div block </p>
	<div class="large ">
		<img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1627986342-101156.png" alt="image">	
	</div>	
</body>
</html>

Output

Here is the output of the above program.

autofit image

Using object-fit property

The object-fit: cover property is used to specify how the image can be resized to fit the div container. It preserves the aspect ratio and fills up the space to cover the div container.

Example: Fit an image to div container using object-fit property

In the given example, we have demonstrated that how the object-fit property fits the image to the div container.

Conclusion

We can resize the image to fit the div container using height and width properties or object-fit properties. We have explained in our examples with working code.



About the author: