Resize Image Proportionally With CSS - GeeksforGeeks

The resize image property is crucial for responsive web design, ensuring images automatically resize to fit their container. The max-width property in CSS is commonly used for this purpose. Note that the resize property won’t work if the width and height of the image are defined in the HTML.

Syntax

img { max-width:100%; height:auto; }

Width can also be used instead of max-width if desired. The key is to use height:auto to override any height=”…” attribute already present on the image. The CSS properties max-width and max-height work great, but aren’t supported many browsers.

Example 1: Resizing with max-width

In this example we have a image within a div while adding padding around it. The image adjusts its width responsively to fit its container.

html <!DOCTYPE html> <html> <head> <title>cell padding</title> <style> .gfg{ width:auto; text-align:center; padding:20px; } img{ max-width:100%; height:auto; } </style> </head> <body> <div class="gfg"> <p id="my-image"> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png"> </p> </div> </body> </html>

Output:

A common use is to set max-width: 100%; height: auto; so large images don’t exceed their containers width. Another way is the use of object-fit property, this will fit image, without changing the proportionally. 

Example 2: Resizing with object-fit

In this example we have an image within a div, applying padding and ensuring the image resizes responsively while maintaining its aspect ratio using CSS’s object-fit: contain property.

html <!DOCTYPE html> <html> <head> <title>cell padding</title> <style> .gfg{ width:auto; text-align:center; padding:20px; } img{ width:100%; height:100%; object-fit:contain; } </style> </head> <body> <div class="gfg"> <p id="my-image"> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png"> </p> </div> </body> </html>

Output:

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.

Using max-width: 100%; height: auto; ensures images scale down to fit their containers in responsive design. The object-fit property can also be used to maintain image proportions. CSS is foundational for web development, providing essential styling for websites and web apps. To master CSS, follow comprehensive tutorials and examples.

author shefali163 Follow Improve Previous Article CSS Border Images Next Article CSS Forms Styling

Please Login to comment...

Từ khóa » Html Scale Image To Fit Screen