In Part 3, we looked at display density descriptors and concluded that they are great for fixed width images, but are insufficient for flexible images.
Flexible images is where srcset’s width descriptors shine.
The syntax for width descriptors is similar to that of display density descriptors. The value of the srcset attribute is a comma-separated list of image sources and descriptors.
The difference is that instead of having 1x, 2x, and other values representing the density, we now list the width of the image source such as 320w, 480w, etc.
<img src="cat.jpg" alt="cat" srcset="cat-160.jpg 160w, cat-320.jpg 320w, cat-640.jpg 640w, cat-1280.jpg 1280w">
The width of the image source can cause some confusion. Width descriptors are looking for the resolution of the source file.
In other words, if you open the image in an image editor, what does it say the resolution is? Grab the width and put it in the srcset attribute.
When you use width descriptors, you’re providing the browser with a list of images and their true widths so that it can select the best source. How does the browser do that?
Your first instinct is probably to say that the browser looks at the size of the element in the page and compares it to the list of source sizes. That makes sense, but it isn’t how the selection work.
See, when a browser starts downloading images, it often doesn’t know the size of the image in the page.
If you look at a timeline of how a browser renders a page, you’ll notice something striking.
The only thing that the browser does know is the size of the viewport. Once we move past display density descriptors, everything hinges on the size of the viewport.
The viewport can be a poor substitute for the actual size of the image. Take the images on Walmart’s Grocery site:
On narrow viewports, the images are nearly the same size as the viewport width. They are certainly close enough to work.
Wider screens, however, are a different matter:
In the second example, the viewport is 1540px wide, but the images are only 254px wide. Knowing the size of the viewport won’t tell the browser enough information to be able to select the right image source.
How do we tell the browser about the size of the image in the page so that it can download the right source from our srcset list? Use the sizes attribute!
Read more in Part 5: Sizes.