CodeBlanks Logo Icon CodeBlanks

Responsive images

CSS course · Intermediate · Lesson 50/98

Make images responsive with max-width: 100%.

max-width: 100% on images

The simplest way to make an image responsive is max-width: 100%. It ensures the image never exceeds its container; it shrinks automatically on narrow screens.

img {
  max-width: 100%;
}

The percentage is relative to the container. The image never grows past its original size; it only shrinks when the container narrows. width: 100%, by contrast, always stretches the image to the container, which can hurt quality.

Why height: auto?

To keep the image from getting squished out of proportion when its width changes, add height: auto. The browser recalculates the height to preserve the aspect ratio.

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

Together these are the classic responsive image recipe: the image fits the container, shrinks on narrow screens, and never gets stretched to the wrong ratio.

Responsive image practice

Modern HTML lets you serve different image files for different screen sizes: <img srcset> and the <picture> element. CSS still works as a universal safety net:

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

Adding this as a base for every image on the site also prevents accidental horizontal scrolling.

Exercise A responsive image style for img

Add max-width: 100% and height: auto declarations to an img selector. The image should fit the container and keep its aspect ratio.

Show example solution
/* Fit the image to the container, keep its ratio */
img {
  max-width: 100%;
  height: auto;
}

Test yourself

  1. What does img { max-width: 100% } do?

    img {
      max-width: 100%;
    }
    • It always stretches the image to the container
    • It shrinks the image below its original size
    • It shows the image at a fixed 100px width
    • It keeps the image inside the container and shrinks it when the container narrows
    Show answer

    It keeps the image inside the container and shrinks it when the container narrows — Correct. max-width: 100% fits the image to the container; when the container narrows, the image shrinks.

  2. Complete the responsive image declaration

    img {
      max-width: 100%;
      ____: auto;
    }
    Show answer
    img {
      max-width: 100%;
      height: auto;
    }
  3. Match the image terms

    max-width: 100%
    Fit to container
    height: auto
    Keep aspect ratio
    width: 100%
    Always fill container
    srcset
    Serve different files

All lessons in Intermediate