![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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>
Advertisements