Responsive Images: srcset and sizes

Intermediate · 10 min

How srcset and sizes let the browser pick an image file by width and pixel density, with the selection results from a real browser at several viewports.

Before thisImages and Alt Text

Web Dev Simplified · 14 min

Responsive Images: srcset and sizes

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `srcset` lists candidate files with their real widths (`800w`) or densities (`2x`). The browser chooses one, so you describe the options and it decides.
  • `sizes` tells the browser how wide the image will be on screen, before CSS loads. With `w` descriptors the browser multiplies that slot width by the device pixel ratio and takes the smallest file at least that wide.
  • In a test with candidates of 400, 800 and 1600 pixels at `sizes="100vw"`, a 400px viewport picked 400w at 1x, 800w at 2x and 1600w at 3x, because 3x needs 1200 and the next file up is 1600.
  • Without `sizes`, the browser assumes the image fills the viewport. At 1000px wide and 1x that picked the 1600w file even when CSS shows the image at half width.
  • A browser may keep a larger file it already has. In a test a viewport grown from 400 to 1200 picked 1600w, and shrinking back to 300 kept it.

One file does not fit every screen

If you serve a 2400-pixel photograph, a phone on mobile data downloads pixels it will never show. If you serve a 400-pixel one, a large high-density display shows a blurry image. The fix is to offer several files and let the browser choose. It is the only one who knows the screen width, the pixel density, and sometimes the connection.

<img
  src="photo-800.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
  sizes="(min-width: 800px) 50vw, 100vw"
  alt="A heron on a frozen lake"
  width="1600" height="1000">

srcset lists candidates. Each ends with a width descriptor, the file’s real width in pixels (400w). sizes says how wide the image will be displayed. src stays as the fallback for browsers that don’t understand either, which today is almost none: the Baseline data in web-features lists srcset and sizes as widely available since September 2019.

Why sizes exists

You might ask why the browser can’t just read the CSS. The reason is timing. Browsers start fetching images as soon as the HTML is parsed, long before stylesheets load and layout runs. At that moment the browser knows the viewport width and the pixel ratio, but not how wide your CSS will make the image. sizes is your declaration of that width, in markup, so the choice can happen early. It’s a promise about the layout, and if the promise is wrong, so is the choice. A media-query-style sizes list uses the same conditions you’d write in CSS, and the first match wins.

How the browser chooses

The rule is: slot width times device pixel ratio gives a needed width, and the browser takes the smallest candidate that’s at least that wide. I verified it in headless Chromium 159, with a 400w, an 800w and a 1600w candidate:

Viewport Pixel ratio sizes Needed Picked
400 1x 100vw 400 400w
400 2x 100vw 800 800w
400 3x 100vw 1200 1600w
1000 1x 100vw 1000 1600w
1000 1x (min-width: 800px) 50vw, 100vw 500 800w
1000 2x (min-width: 800px) 50vw, 100vw 1000 1600w
1000 1x none given 1000 1600w
3000 1x 100vw 3000 1600w (largest available)

Row three shows why you want several steps: 1200 needed, 800 too small, so the 1600 file loads. The no-sizes row shows the default, which is 100vw. If your image only fills half the page, leaving sizes off makes the browser overestimate and download a bigger file than it needs. The standards don’t promise one exact algorithm: browsers may choose differently, for example to save data. My results are one browser at one version.

With x descriptors, the logic is simpler. srcset="a.png 1x, b.png 2x" loaded a.png at a pixel ratio of 1 and b.png at 2. Use that when the CSS size is fixed on every screen, such as an avatar.

Resizing and caching

The choice isn’t made once. In a test I loaded a page at 400px, which picked the 400w file, then resized the window to 1200px: it fetched the 1600w file. Shrinking back to 300px kept the 1600w file. A browser that already holds a larger image may reuse it rather than download a smaller one, so don’t expect currentSrc to go back down. You can read the chosen file from img.currentSrc in the console, which is how I recorded each result above.

Also give the image width and height so its box is reserved, as covered in images and alt text. For art-directed crops rather than different sizes of the same picture, use picture. The CSS side, object-fit and max-width, is in sizing images and replaced elements.

What the video covers

The embed is a clip, 0:00 to 10:12, from Web Dev Simplified’s “Make Your Site Lightning Fast With Responsive Images” (June 2023, 14 minutes). The chapters in the clip are the introduction (0:00), img srcset attribute basics (0:43) and img srcset attribute advanced (6:35). The last chapter, the picture element (10:12), is left for the next lesson. I could not read a transcript, so I describe it only from the chapters and description. The selection table and the resize test are this lesson’s own. The deeper link is Kevin Powell’s 30-minute 2018 treatment of srcset and sizes, which is slower but exhaustive.

Where this fits

This moves from one image in images and alt text to one image at many sizes. Next, the picture element and art direction covers changing the crop or format, and lazy loading covers when the chosen file loads. The CSS lesson on aspect ratio and responsive media overlaps on layout.

Check yourself

  1. 01What does `sizes="(min-width: 800px) 50vw, 100vw"` tell the browser?

    That the image will be half the viewport wide at 800px and above, and full width below that. It's a layout prediction the browser uses to choose from `srcset`. In a test at 1000px wide and 1x, that sizes value picked the 800w file, where plain `100vw` picked 1600w.

  2. 02Why must `sizes` be written in markup instead of being read from the CSS?

    The browser starts fetching images before the stylesheet has loaded and layout exists, so it can't measure the final width. `sizes` is your promise about the layout, written where the browser can read it early. If it is wrong, the browser picks a wrong file.

  3. 03You offer `a-400.jpg 400w` and `a-800.jpg 800w`. A phone with a 2x screen shows the image 400 CSS pixels wide. Which file loads?

    The 800w file. The needed width is 400 times the device pixel ratio of 2, which is 800, and the browser takes the smallest candidate at least that wide. In a test a 400px viewport at 2x with `sizes="100vw"` chose the 800-pixel file.

  4. 04When would you use `2x` descriptors instead of `w` descriptors?

    When the image has a fixed CSS size on every screen, such as an avatar or logo, so only density varies. For fluid images whose width changes with the layout, `w` plus `sizes` is the right tool.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark