We set mydiv to auto height and width to allow"/> We set mydiv to auto height and width to allow">

Home >Web Front-end >CSS Tutorial >How to automatically resize an image to fit a div container using CSS?

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

WBOY
WBOYforward
2023-09-09 22:01:011153browse

To automatically resize the image to fit the div container, we set the following CSS fproperty or img tag -

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

First, we set the image using the img tag in the div mydiv -

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

We set mydiv to auto height and width to allow automatic resizing of the div -

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

The image in mydiv now has the following CSS properties max-width and max-height set to allow automatic resizing without any issues -

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

Example

Now let’s see a complete example of automatically resizing 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

如何使用 CSS 自动调整图像大小以适合 div 容器?

The above is the detailed content of How to automatically resize an image to fit a div container using CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete