Why Images Need max-width: 100%

In web design, a common issue happens when an image is wider than the box (container) that holds it. The container might be small (such as width: 200px), but the image might be large (such as 400px wide).

If we do nothing, **the image will overflow out of its container**, breaking the layout. To prevent this, we often give images this CSS:

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

This does not mean “make the image 100% of its own natural width”. It means:

“Make the image no wider than 100% of the width of the container it is inside.”

So if the container is only 200px wide, the 400px image shrinks down to fit.

Example

❌ Image without max-width: 100%
Example image 400px wide

The article is only 200px wide → image overflows!

✅ Image with max-width: 100%
Example image 400px wide

The image now shrinks to match the 200px container.

The image is the same 400px wide image file in both cases.

Why This Works

When CSS sees max-width: 100% on an image:

This is why responsive web design almost always uses max-width: 100% on images — it prevents layout breakage on small screens or narrow columns.

Images in a CSS Grid: max-width vs width

In a grid layout, each grid cell can be a percentage of the screen. But what happens if the image inside the cell is too small to fill it?

Below, each grid item is 40% of the screen width (which will usually be over 200px wide). The image is a small image at only 200px-wide.

❌ Using max-width: 100%
Small example image

The image is only 200px wide. Because it uses max‍-‍width: 100%, it will not stretch. It stays at its natural size, so it looks small inside the grid cell.

✅ Using width: 100%
Small example image

Here, width: 100% forces the image to stretch to fill the entire grid cell. This makes the grid layout look more consistent.

When to Use Each

Important Note About Image Quality

If the image is too small, stretching it with width: 100% will cause pixelation or blurriness. The solution is to use a larger or higher-resolution image.