Open In App

Resize image proportionally with CSS

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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: 

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=
        </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: 

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=
        </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.



Last Updated : 03 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads