Open In App

How to Force Image Resize and Keep Aspect Ratio in HTML ?

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To resize an image in HTML while keeping its aspect ratio, you can use simple HTML or CSS techniques. The problem is to ensure that the image scales without distortion or cropping. This can be fixed by applying simple styles that resize the image while keeping its original proportions.

Below are the various methods to force image resize and keep the Aspect Ratio:

1. Using CSS max-width and max-height Property

One simple and effective way to force image resize while preserving the aspect ratio is by using CSS. You can set the max-width and max-height properties to limit the size of the image, ensuring it resizes proportionally.

Example: In this example, the .resizable-image class is applied to the image, setting both max-width and max-height to 100%. This ensures that the image won't exceed the size of its container while maintaining its aspect ratio.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        How to force image resize and
        keep aspect ratio?
    </title>

    <style>
        .resizable-image {
            max-width: 100%;
            max-height: 100%;
            display: block;
            margin: auto;
        }
    </style>
</head>

<body>
    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20230427130955/CSS-Tutorial.webp" alt="Resizable Image"
        class="resizable-image">
</body>

</html>

Output

2. Using the width Attribute

You can use the width attribute directly on the img tag to specify the desired width. The browser will automatically adjust the height to maintain the aspect ratio.

Example: This HTML code creates a responsive image that maintains its aspect ratio while being centered on the page.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        How to force image resize and
        keep aspect ratio?
    </title>

    <style>
        .resizable-image {
            display: block;
            margin: auto;
        }
    </style>
</head>

<body>
    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20230427130955/CSS-Tutorial.webp" 
         alt="Resizable Image"
         class="resizable-image" width="600">
</body>

</html>

Output


Next Article

Similar Reads