References

Beginner-friendly references for web development, with live, editable examples.

The HTML srcset attribute

Attribute All modern browsers
In short

The HTML srcset attribute provides a set of candidate images for the browser to choose from based on screen density or width. It is used on the <img> and <source> elements.

Overview

The srcset attribute provides a set of candidate images for the browser to choose from based on screen density or width. It applies to the <img> and <source> elements.

Pair width descriptors (w) with the sizes attribute so the browser can pick the best file before layout.

Syntax

<img src="m.jpg" srcset="s.jpg 480w, l.jpg 1080w" sizes="(max-width:600px) 480px, 1080px" alt="">

Values

Value
A comma-separated list of "URL descriptor" pairs, e.g. small.jpg 480w, large.jpg 1080w or 1x/2x.

Best practices

  • Make each w value in srcset the file's real pixel width. If a 400-pixel file carries an 800w label and no CSS width is set, it shows at half size, because the browser divides w by the slot size to get a density.
  • Stick to one descriptor type within a srcset, and don't repeat a value. A URL with no descriptor counts as 1x and clashes with an explicit 1x entry.
  • Add the src file to srcset when you use w descriptors, because the browser leaves src out of the choice then. With x descriptors, src counts as 1x unless srcset has its own 1x entry.
  • Percent-encode spaces in file names as %20. Whitespace ends a candidate's URL, which turns my photo.jpg 2x into a broken candidate that the browser drops.
  • Inspect the image's currentSrc property to see which candidate loaded. The choice is implementation-defined, so the same markup can fetch different files on different screens and browsers.

Frequently asked questions

What does the srcset attribute do?
Lists responsive image candidates.
How do I make images responsive?
Use srcset with sizes on the <img>, or a <picture> for art direction and modern formats.
How do I stop images causing layout shift?
Set the width and height attributes (or a CSS aspect-ratio) so the space is reserved.
Which elements use the srcset attribute?
It is an element-specific attribute, used on the <img> and <source> elements.