Search code examples
htmlimagemedia-queriespolyfillssrcset

Picturefill 2: What is the purpose of the sizes attribute?


I'm trying to understand what the sizes attribute is for exactly in the PictureFill 2.0 polyfill. Here are some basic examples:

<img sizes="100vw, (min-width: 40em) 80vw"
srcset="pic-small.png 400w, pic-medium.png 800w, pic-large.png 1200w" alt="test">

<img sizes="(min-width: 40em) 80vw, 100vw"
srcset="medium.jpg 375w, medium.jpg 480w, large.jpg 768w" alt="A car">

According to the documentation:

The sizes syntax is used to define the size of the image across a number of breakpoints. srcset then defines an array of images and their inherent sizes.

So the sizes attribute defines the size of the image across breakpoints. Isn't that what CSS is for? Why would you be defining CSS-like rules for how an image is displayed in an HTML attribute? What am I missing here?

On a side note, why does the OFFICIAL DOCUMENTATION say:

It's beyond the scope of this guide to get into much detail about how to use the new srcset & sizes attributes...

wtf? That made me laugh. Isn't that was documentation is for?


Solution

  • The sizes attribute decides which version of the image that you listed in srcset will be used in the current rendering of the webpage.

    You are right. It's duplication if you already define image sizes in CSS across breakpoints. But it seems that the browsers do not support extracting that information from CSS and using it for pre-calculating image sizes. So it's a duplication that is needed currently.

    More information here and ideas for future development here: http://ericportis.com/posts/2014/separated/

    I learned about the lazySizes javascript today, which does this exact job by the way. It extracts this information from CSS, and puts it into the sizes attribute of img. It worked wonderfully for me.