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



To auto-resize an image to fit a div container, we have set the following CSS fproperty or the img tag −

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

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>

We have set the mydiv with height and width auto to allow auto-resize the div −

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

Now, the image in the mydiv 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 complete 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>

Output


Advertisements