2

The <picture> element has been working in Chrome for over a year, but I can't get the sizes attribute of <source> to work.

The following displays the correct image for the breakpoints in the media queries, but the images are displayed at their default sizes instead of using the values specified in the sizes attribute.

<picture>
   <source media="(min-width: 600px)" 
           sizes="50vw"
           srcset="img1.jpg">
   <source media="(min-width: 400px)"
           sizes="90vw"
           srcset="img2.jpg">
   <img src="img3.jpg" alt="my image">
</picture>

Am I missing something?

tronman
  • 9,862
  • 10
  • 46
  • 61

1 Answers1

4

You need to use w descriptors when using the sizes attribute, otherwise it has no effect.

Error: Bad value img1.jpg for attribute srcset on element source: No width specified for image img1.jpg. (When the sizes attribute is present, all image candidate strings must specify a width.)

https://validator.nu/

So your HTML should read:

<picture>
   <source media="(min-width: 600px)" 
           sizes="50vw"
           srcset="img1.jpg 300w">
   <source media="(min-width: 400px)"
           sizes="90vw"
           srcset="img2.jpg 200w">
   <img src="img3.jpg" alt="my image">
</picture>

Though if you only have one candidate per source, you could use CSS instead to size the image appropriately for different breakpoints and skip sizes/w. The primary function of sizes is to give a hint to the browser which of the resources in srcset to load; that it affects the intrinsic size is more of a side-effect.

tronman
  • 9,862
  • 10
  • 46
  • 61
zcorpan
  • 1,243
  • 6
  • 11