Open In App

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

When working with images on the web, maintaining the aspect ratio is essential for a visually appealing and consistent presentation. This article explores various approaches to force image resize while preserving the aspect ratio in HTML, covering different methods based on your specific requirements.

Method 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.



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.

Example:






<!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=
        alt="Resizable Image"
        class="resizable-image">
</body>
  
</html>

Output:

Method 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:




<!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=
        alt="Resizable Image" 
        class="resizable-image" 
        width="600">
</body>
  
</html>

Output:


Article Tags :