htmlimageresponsive-imagessrcset

Understanding srcset and sizes in combination with HiDPI monitors


I have been into CSS for quite a while now, but srcset and sizes for the image element confuse me. Here is an example that I thought would work.

<img alt="Background image flowers"
    srcset="img/flowers-480.jpg 480w,
            img/flowers-480@2x.jpg 480w 2x,
            img/flowers-768.jpg 768w,
            img/flowers-768@2x.jpg 768w 2x,
            img/flowers-960.jpg 960w,
            img/flowers-960@2x.jpg 960w 2x,
            img/flowers-1280.jpg 1280w,
            img/flowers-1280@2x.jpg 1280w 2x" 
    sizes="(max-width: 1279px) 100vw,
           (min-width: 1280) 1280px"
    src="img/flowers-960.jpg">

The idea is to have an image that's 100% of the viewport until the viewport is 1280px wide or wider, then the image will be fixed size. However, to compensate for higher DPI devices I thought it was recommended to add DPI descriptors (1.5x, 2x and so on), as suggested here and here.

What I thought the above code would do is:

However, when I put this through a validator I get the following error:

Error: Bad value for attribute srcset on element img: Width for image img/flowers-480@2x.jpg is identical to width for image img/flowers-480.jpg

So clearly I am completely missing the point of how srcset and sizes work. What am I doing wrong?


Solution

  • As defined on MDN for <img srcset="...">:

    Each string is composed of:

    a URL to an image, optionally, whitespace followed by one of:

    • a width descriptor, or 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.
    • a pixel density descriptor, which is a positive floating point number directly followed by 'x'.

    You tried to use both, and that's illegal.