What is the relationship between "srcset" and "sizes" attributes?

Suppose I'm using this <img> element below (the code has been taken from MDN):

<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg"
     alt="Elva dressed as a fairy">

As you can see, there are two options in the srcset attribute and two options for the sizes attribute. But can those be different? Can it be like 2 for srcset and 3 for sizes or the other way round?

Upvotes: 1

Views: 69

Answers (1)

Nicolas Hoizey
Nicolas Hoizey

Reputation: 2031

srcset lists the available image files, while sizes defines the image's rendering dimensions at different breakpoints, so you can have very different numbers of items in each.

For example, you could have more available images (here we add one for large screens with a density of at least 2dppx):

<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w,
             elva-fairy-1600w.jpg 1600w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg"
     alt="Elva dressed as a fairy">

sizes depends on the various layouts the page have across the viewport widths, so you often have as many sizes item as different layouts.

Upvotes: 1

Related Questions