Search code examples
htmlimagecsssrcset

Explain `w` in `srcset` of image


I understand that the srcset is used to determine which image to load based on the dpi of the device. I came across this example on the Google Web Fundamentals which seems to use the w unit along with the vw unit which just happens to be the 1 % ofviewport width:

<img src="lighthouse-200.jpg" sizes="50vw"
     srcset="lighthouse-100.jpg 100w, lighthouse-200.jpg 200w,
             lighthouse-400.jpg 400w, lighthouse-800.jpg 800w,
             lighthouse-1000.jpg 1000w, lighthouse-1400.jpg 1400w,
             lighthouse-1800.jpg 1800w" alt="a lighthouse">

Help me understand what the unit of measure for this is and how I can use it?


Solution

  • According to MDN the w refers to:

    a width descriptor (a positive integer directly followed by w). The width descriptor is divided by the source size given in the sizes attribute to calculate the effective pixel density.

    Additionally, the W3 states:

    The user agent will calculate the effective pixel density of each image from the specified w descriptors and the specified rendered size in the sizes attribute. It can then choose any of the given resources depending on the user’s screen’s pixel density, zoom level, and possibly other factors such as the user’s network conditions. If the user’s screen is 320 CSS pixels wide, this is equivalent to specifying wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x. On the other hand, if the user’s screen is 1200 CSS pixels wide, this is equivalent to specifying wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x. By using the w descriptors and the sizes attribute, the user agent can choose the correct image source to download regardless of how large the user’s device is.

    Example 13 on the W3 page provides additional detail.