0

I'm trying to use a (max-width: ...) along with a default size specification in the sizes attribute of an <img srcset...>. However, this does not work as I'd expect. I created the following test case:

<p>
  <b>Viewport width</b>: <span id="width"></span><br>
  <b>Device pixel ratio</b>: <span id="ratio"></span><br>
<p>

<h3>Max-width + default (break @1600)</h3>
<img
  srcset="https://via.placeholder.com/1100x200 1100w, 
          https://via.placeholder.com/2000x400 2000w"
  sizes="(max-width: 1600px) 1100px, 2000px" 
  src="https://via.placeholder.com/300x400" class="full-width">

<h3>Without sizes</h3>
<img
  srcset="https://via.placeholder.com/1100x200 1100w, 
          https://via.placeholder.com/2000x400 2000w"
  src="https://via.placeholder.com/300x400" class="full-width">

See my Codepen here

What I expect the browser to do is to use the low res image below a viewport width of 1600px (or 800px on a double density screen) and the high res image in all other cases. However, both Firefox 104 and Chrome 105 ALWAYS render the high res image.

I've tested this in "Responsive" mode with network caching disabled and hard reloads every time, starting from the lowest resolution to the higher one, ensuring that the high res image wasn't loaded from the start. And as you can see that only works as expected when I don't specify any sizes (in which case the browser simply switches when the viewport width exceeds the low res image width):

Srcset with and without sizes

What am I doing wrong here and how do I get the expected behavior using the max-width specification in sizes?

Pascal Lindelauf
  • 4,782
  • 4
  • 40
  • 55
  • For me, Firefox 104 renders the small image and when widening the window the large one is loaded, just as exepected. Chromium 102 however always uses the large image. My displays have a 1x density, maybe yours is higher. – cweiske Oct 14 '22 at 10:00
  • Chromium keeps the high source once it loaded it: https://stackoverflow.com/questions/28650327/responsive-images-srcset-not-working – cweiske Oct 14 '22 at 10:06
  • I tried all the options in Chrome that are described in the top rated answer, including right-clicking the reload button and selecting "Empty cache and hard reload". I also took the pixel density into account (see the screenshot, which says "Device pixel ratio: 2"), but no matter how I try: if I start at a width of 320px, it only loads the 2000x400 image instead of the 1100x200 image. So I'm still extremely puzzled as to why this isn't working. I'm still hoping anyone else has suggestions... – Pascal Lindelauf Oct 25 '22 at 13:52

0 Answers0