Resize image proportionally with CSS

The resize image property is used in responsive web where image is resizing automatically to fit the div container. The max-width property in CSS is used to create resize image property. The resize property will not work if width and height of image 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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=
            </p>
        </div>
    </body
</html>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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=
            </p>
        </div>
    </body
</html>                    

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.