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

WBOY
Release: 2023-09-09 22:01:01
forward
1123 people have browsed it

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%;
Copy after login

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>
Copy after login

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

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

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;
}
Copy after login

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!