Use CSS width property for responsive image

The CSS width property is essential for creating responsive images that automatically scale with their container. Setting the width to 100% makes an image responsive by ensuring it never exceeds its parent container's width.

Syntax

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

Example

The following code demonstrates how to make an image responsive using the width property −

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            border: 2px solid #ccc;
        }
        
        .responsive-img {
            width: 100%;
            height: auto;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <p>This image will resize based on the container width:</p>
        <img src="https://www.tutorialspoint.com/python/images/python-data-science.jpg" 
             alt="Python Data Science" 
             class="responsive-img">
    </div>
</body>
</html>
An image that automatically scales to fit within its container. The image maintains its aspect ratio and never overflows the container width, making it responsive across different screen sizes.

Key Properties

Property Value Purpose
width 100% Makes image scale to container width
height auto Maintains aspect ratio
max-width 100% Prevents image from exceeding original size

Conclusion

Using width: 100% with height: auto creates responsive images that adapt to different screen sizes while maintaining their proportions. This technique is fundamental for responsive web design.

Updated on: 2026-03-15T13:08:46+05:30

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements