How to auto-resize an image to fit a div container using CSS?


On a web page if you want to auto-resize an image to fit a div, you need to work around tne heigh, width, max-width and max-height properties. To auto-resize an image to fit a div container, we have set the following CSS properties on the img tag −

max-width: 100%;
max-height: 100%;

Set an Image

First, we have set an image using the img tag in the div mydiv −

<div id="myDiv">
   <img src="https://www.tutorialspoint.com/behave/images/behave.jpg">
</div>

Style the Container Height and Width

We have set the mydiv with height and width auto to allow auto-resize the div. If height: auto; the element will automatically adjust its height to allow its content to be displayed correctly as shown below −

#myDiv {
   height: auto;
   width: auto;
   border: 2px solid blue;
}

Style the Image Inside the Container

Now, the image in our divv is set with the following CSS properties max-width and max-height to allow auto-resize without any problem −

#myDiv img {
   max-width: 100%;
   max-height: 100%;
   margin: auto;
   display: block;
}

Example

Let us now see the example to auto-resize an image to fit a div container using CSS −

<!DOCTYPE html>
<html>
<head>
   <style>
      #myDiv {
         height: auto;
         width: auto;
         border: 2px solid blue;
      }

      #myDiv img {
         max-width: 100%;
         max-height: 100%;
         margin: auto;
         display: block;
      }
   </style>
</head>
<body>
   <div id="myDiv">
      <img src="https://www.tutorialspoint.com/behave/images/behave.jpg">
   </div>
</body>
</html>

Updated on: 16-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements