W3C Validation of SRCSET

eat-sleep-code picture eat-sleep-code · Apr 22, 2015 · Viewed 7.1k times · Source

W3C Validator is throwing an error on the following code:

<img alt="My Unique Alternative Text" class="news-image-left" height="480" src="/images/en-us/news/20140214-01.jpg" srcset="/images/en-us/news/20140214-01.jpg 1x, /images/en-us/news/20140214-01-mobile.jpg 640w" style="border-width: 0px;" title="A Unique Image" width="1420" itemprop="image">

The error is:

Bad value /images/en-us/news/20140214-01.jpg 1x, /images/en-us/news/20140214-01-mobile.jpg 640w for attribute srcset on element img: No width specified for image /images/en-us/news/20140214-01.jpg. (Because one or more image candidate strings specify a width (e.g., the string for image /images/en-us/news/20140214-01-mobile.jpg), all image candidate strings must specify a width.)

So, how do I specify both an image for pixel density (1x) -- down the road I may want to do one for high-density displays (2x) and for displays less than 640 pixels wide? That is, in a way that will make the W3C validator happy.


UPDATE:

Well, I tinkered around some more with it and now the validator is no longer complaining but it doesn't appear to be working right so I don't think I have won the battle yet.

I now have this:

<img alt="My Unique Alternative Text" class="news-image-left" height="480" src="/images/en-us/news/20140214-01.jpg" srcset="/images/en-us/news/20140214-01-mobile.jpg 320w" sizes="(min-width:640px) 1420px, 320px" style="border-width: 0px;" title="A Unique Image" width="1420" itemprop="image"> 

BUT, now on Chrome I am getting just the "-mobile" image, regardless of how wide my screen is. I want it to display the full 1420px wide image on any display that is wider than 640px.

I am guessing I have just one thing out of place... any help would be appreciated.

Answer

alexander farkas picture alexander farkas · Apr 26, 2015

This answers only for your update: The reason for this is, that the browser chooses one candidate from your srcset, the src attribute is used as a fallback. This means to get the larger candidate you need to also add it to your srcset:

<img srcset="/images/en-us/news/20140214-01-mobile.jpg 320w, /images/en-us/news/20140214-01.jpg 1420w" sizes="(min-width:640px) 1420px, 320px" />

I don't really know your image layout, but I doubt, that sizes is correct here. If this image is displayed fullwidth until 1420px your sizes attribute should look like this.

sizes="(min-width: 1420px) 1420px, 100vw"

or

sizes="(max-width: 1420px) 100vw, 1420px"

Additionally you should use more images. Note if you use the width descriptor the browser automatically handles the density for you (for retina devices). Use at least 640w, 980w/1024w, 1420w, 2048w.