Set the width of an image with CSS

The CSS width property is used to set the width of an image. This property can have values in pixels, percentages, or other CSS length units. When using percentage values, the width is calculated relative to the containing element.

Syntax

img {
    width: value;
}

Common Width Values

The width property accepts several types of values:

  • Pixels (px) - Fixed width in pixels
  • Percentage (%) - Width relative to parent container
  • Auto - Browser calculates width automatically
  • Viewport units (vw) - Width relative to viewport

Example: Setting Image Width with Pixels and Percentage

<!DOCTYPE html>
<html>
<head>
    <style>
        .fixed-width {
            border: 2px solid green;
            width: 150px;
        }
        .percentage-width {
            border: 2px solid blue;
            width: 50%;
        }
        .container {
            width: 300px;
            border: 1px solid red;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h3>Fixed Width (150px)</h3>
    <img class="fixed-width" src="/images/tutorialspoint-logo.png" alt="TutorialsPoint Logo" />
    
    <h3>Percentage Width (50% of container)</h3>
    <div class="container">
        <img class="percentage-width" src="/images/tutorialspoint-logo.png" alt="TutorialsPoint Logo" />
    </div>
</body>
</html>

Example: Responsive Image Scaling

<!DOCTYPE html>
<html>
<head>
    <style>
        .responsive-img {
            width: 100%;
            max-width: 400px;
            height: auto;
            border: 2px solid purple;
        }
        .small-img {
            width: 80px;
            height: auto;
        }
    </style>
</head>
<body>
    <h3>Responsive Image (100% width, max 400px)</h3>
    <img class="responsive-img" src="/images/tutorialspoint-logo.png" alt="Responsive Logo" />
    
    <h3>Small Fixed Image (80px)</h3>
    <img class="small-img" src="/images/tutorialspoint-logo.png" alt="Small Logo" />
</body>
</html>

Key Points

  • Always include height: auto to maintain aspect ratio when setting width
  • Use max-width: 100% to prevent images from overflowing their containers
  • Percentage widths are calculated relative to the parent element's width
  • Combining width: 100% with max-width creates responsive images

Best Practices

For responsive design, use percentage or viewport units instead of fixed pixel values. Always set height: auto to preserve the image's aspect ratio and prevent distortion.

Conclusion

The CSS width property provides flexible options for controlling image dimensions. Use pixels for fixed layouts, percentages for responsive designs, and combine with max-width for optimal responsiveness.

Updated on: 2026-03-15T23:18:59+05:30

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements