Signup/Sign In

How do I auto-resize an image to fit a div container?

When you add an image within a given element, it is important that it fits well in the element or resize itself according to the container size.

It is possible to auto-resize the images in HTML using CSS properties. There are several ways to resize an image so that it fits into the given container. Let us discuss them one by one.

Using height and width properties

We can use CSS height and width properties so that the image fits the div container. Here, we used height: 100% and width: 100% CSS style sheet to the image.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>
  .container{
    width: 40%;
	height: 250px;
	border: 5px solid blue;
  }
  img {
   height: 100%;
   width: 100%;
  }
</style>
<body>
    <h2> Image that fits container </h2>
    <div class="container">
	  <img src="pic1.png" alt="pic1">
	 </div>
</body>
</html>

Output

Here in the output, you can see that the image fits into the given div container.

image fits

Using object-fit property

There is another way to resize the image to fit the div container.

The object-fit property of CSS specifies how an <img> or <video> should be resized to fit into the given container.

The value used for object-fit: cover which is used to maintain the aspect ratio while filling the image to the div container.

If the aspect ratio of the image does not match the aspect ratio of the container then the image will be clipped.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>
  .container{
    width: 40%;
	height: 250px;
	border: 5px solid blue;
  }
  img {
   height: 100%;
   width: 100%;
   object-fit: cover;
  }
</style>
<body>
    <h2> Image that fits container </h2>
    <div class="container">
	  <img src="pic1.png" alt="pic1">
	 </div>
</body>
</html>

Output

We can see in the given output that the image has been clipped from the sides. So, here though the container is covered with the image but the image has been clipped.

clipped image

Using max-width and max-height properties

We can use max-width and max-height properties to images to auto-resize the image. Let's take a simple example to illustrate this.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>  
  img {
   max-width: 100%;
   max-height: 100%;
   
  }
  .square {
      border: 5px solid blue;
	  height: 100px;
	  width: 100px;
	  }
</style>
<body>
    <h2> Image that fits container </h2>
    <div class="square">
	  <img src="pic1.png" alt="pic1">
	 </div>
</body>
</html>

Output

The image totally covers the div container.

max fits image

Conclusion

Images can be auto-sized to cover the div container using CSS properties. Use any one of the above methods to auto-size the image to fit into the div container.



About the author: