Tutorialspoint.dev

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:

<!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>

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:

<!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>                    

Output:



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter