Responsive images with multiple slot widths

The sizes attribute of an <img> element lets the browser know how wide the image will be displayed, so it can select the right file from a srcset. When the layout changes across breakpoints, you can specify a different slot width for each media condition.

Demo behavior

In the demo, reload the app in windows of different sizes. The browser loads different images and applies different layouts depending on the viewport width.

The key logic is in index.html.

How the widths are matched

The sizes attribute in this example declares three display widths:

  • Up to 480px viewport width: the image is displayed at 100% of the viewport width.
  • Between 481px and 1024px viewport width: the image is displayed at 50% of the viewport width.
  • Above 1024px viewport width: the image is displayed at a fixed 800px.

These values mirror the CSS-defined styling at each breakpoint. This allows designs that change image proportions as the viewport changes to still serve appropriately sized image files.

Format of the sizes attribute

The sizes attribute takes a comma-separated list. Each item, except the last, is a media condition followed by a slot width. The media condition can use max-width, min-width, or any other valid media query.

The final item is the fallback slot width and needs no media condition. You may include as many slot width entries as needed; the number of widths does not have to correspond to the number of images listed in srcset.

Valid units for slot widths include:

  • 100px — fixed pixel value
  • 33vw — viewport unit
  • 20em — em unit
  • calc(50vw-10px) — CSS calculation

Percentages, such as 25%, are not valid for the sizes attribute.