Set the height and width of an image using percent with CSS

To set the height and width of an image using percentage values, you can apply CSS properties that make the image responsive to its container's dimensions. This approach is useful for creating flexible layouts that adapt to different screen sizes.

Syntax

img {
    width: percentage;
    height: percentage;
}

Example

The following example demonstrates how to set an image's dimensions using percentage values −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        width: 400px;
        height: 300px;
        border: 2px solid #333;
        padding: 10px;
    }
    
    img {
        width: 50%;
        height: 50%;
        display: block;
        margin: 10px auto;
    }
</style>
</head>
<body>
    <div class="container">
        <p>Image sized at 50% of container:</p>
        <img src="/css/images/logo.png" alt="Sample Image">
    </div>
</body>
</html>
A bordered container appears with an image inside that takes up 50% of the container's width and height, centered within the container.

Key Points

  • Percentage values are relative to the parent container's dimensions
  • Using percentages makes images responsive and flexible
  • The aspect ratio may change if width and height percentages are different
  • Remove any inline width/height attributes to let CSS take control

Conclusion

Using percentage values for image dimensions creates responsive designs that adapt to their container size. This technique is essential for building flexible web layouts that work across different devices and screen sizes.

Updated on: 2026-03-15T12:12:38+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements