Use CSS max-width property for responsive image

The CSS max-width property is essential for creating responsive images that scale down automatically based on their container size. When set to 100%, it ensures images never exceed their parent element's width while maintaining their aspect ratio.

Syntax

img {
    max-width: 100%;
    height: auto;
}

How It Works

The max-width: 100% property prevents images from being larger than their container, while height: auto maintains the image's proportions by automatically adjusting the height based on the width.

Example: Responsive Image

The following example demonstrates how to make an image responsive using the max-width property −

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .container {
            width: 80%;
            margin: 20px auto;
            border: 2px solid #333;
            padding: 20px;
        }
        
        .responsive-img {
            max-width: 100%;
            height: auto;
            display: block;
        }
        
        .fixed-img {
            width: 400px;
            height: 300px;
            display: block;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h3>Responsive Image (scales with container):</h3>
        <img src="/python/images/python-data-science.jpg" alt="Python Data Science" class="responsive-img">
        
        <h3>Fixed Size Image (may overflow):</h3>
        <img src="/python/images/python-data-science.jpg" alt="Python Data Science" class="fixed-img">
        
        <p><em>Resize your browser window to see the difference between responsive and fixed images.</em></p>
    </div>
</body>
</html>
A container with two images appears: the first image (responsive) scales down when the browser is resized while maintaining its aspect ratio, while the second image (fixed) may cause horizontal scrolling on smaller screens.

Key Benefits

  • Prevents overflow: Images won't break out of their containers on smaller screens
  • Maintains aspect ratio: Combined with height: auto, preserves image proportions
  • Mobile-friendly: Ensures images display properly on all device sizes

Conclusion

Using max-width: 100% and height: auto is the standard approach for responsive images. This simple CSS rule ensures images scale appropriately across all devices while maintaining their quality and proportions.

Updated on: 2026-03-15T13:09:02+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements