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

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:

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:

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:




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to use Escape Characters in PHP ? How to use Escape Characters in PHP ?
PHP Program to Print Pascal&#039;s Triangle PHP Program to Print Pascal&#039;s Triangle
Complex Numbers in PHP Complex Numbers in PHP
PHP Program to Convert Enum to String PHP Program to Convert Enum to String
How to Convert Int Number to Double Number in PHP ? How to Convert Int Number to Double Number in PHP ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14