Skip to main content

HTML Guide

When the “srcset” attribute has any image candidate string with a width descriptor, the “sizes” attribute must also be specified.

A srcset attribute with width descriptors requires a sizes attribute on the img element.

When you use width descriptors (e.g., 400w, 800w) in the srcset attribute, the browser needs the sizes attribute to correctly select the appropriate image source based on the layout size in the viewport. Without sizes, the HTML is invalid, and the browser cannot resolve how large the image will be displayed.

Explanation

The srcset attribute allows you to provide multiple image sources for different screen conditions. There are two types of descriptors in srcset: width descriptors (e.g., 400w) and pixel density descriptors (e.g., 2x). When using width descriptors, you must include a sizes attribute to describe the expected display width of the image in CSS pixels. This helps browsers pick the best matching source.

Correct Usage Example

<img
  src="image-400.jpg"
  srcset="image-400.jpg 400w, image-800.jpg 800w"
  sizes="(max-width: 600px) 100vw, 600px"
  alt="Responsive example">

Incorrect Usage Example

<img
  src="image-400.jpg"
  srcset="image-400.jpg 400w, image-800.jpg 800w"
  alt="Responsive example">

(Missing sizes attribute)

Explanation of the correct example:

  • The srcset attribute lists two images with their respective pixel widths.
  • The sizes attribute tells the browser to use 100vw (100% of the viewport width) if the viewport is 600px wide or less, and otherwise use 600px as the display width.

Learn more:

Related W3C validator issues