Home >Web Front-end >CSS Tutorial >How to automatically resize an image to fit a div container using CSS?
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; }
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>
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!