How to scale down an image with CSS to make it responsive

The CSS max-width and height properties can be used to make images responsive, allowing them to scale down automatically based on the container size while maintaining their aspect ratio.

Syntax

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

Key Properties

Property Value Description
max-width 100% Ensures image never exceeds container width
height auto Maintains aspect ratio automatically

Example: Basic Responsive Image

The following example demonstrates how to make an image scale down responsively −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        width: 50%;
        border: 2px solid #ccc;
        padding: 10px;
        margin: 20px auto;
    }
    
    .responsive-img {
        max-width: 100%;
        height: auto;
        display: block;
    }
</style>
</head>
<body>
    <div class="container">
        <img src="/videotutorials/images/coding_ground_home.jpg" 
             alt="Online Compiler" 
             class="responsive-img">
    </div>
</body>
</html>
An image that automatically scales down to fit within its container while maintaining its original aspect ratio. The image never exceeds the container's width.

Example: Multiple Responsive Images

Here's how to apply responsive scaling to multiple images in a layout −

<!DOCTYPE html>
<html>
<head>
<style>
    .gallery {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
    }
    
    .gallery-item {
        flex: 1;
        min-width: 200px;
    }
    
    .gallery img {
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
</style>
</head>
<body>
    <div class="gallery">
        <div class="gallery-item">
            <img src="/videotutorials/images/coding_ground_home.jpg" alt="Image 1">
        </div>
        <div class="gallery-item">
            <img src="/videotutorials/images/coding_ground_home.jpg" alt="Image 2">
        </div>
    </div>
</body>
</html>
A responsive image gallery where images automatically resize to fit their containers, arranged in a flexible layout with rounded corners and shadows.

Conclusion

Using max-width: 100% and height: auto creates truly responsive images that scale down gracefully. This approach ensures images never overflow their containers while preserving their natural proportions.

Updated on: 2026-03-15T12:52:07+05:30

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements