Search code examples
htmlcssfirefoxsrcsetresponsive-images

Srcset not working Firefox


I am trying to use the srcset attribute to swap images when the browser reaches a specific screen size. I need the desktop image to appear when screen size is above 768 pixels wide.

I've been able to accomplish this with the code below in most browsers excluding firefox. I'm pretty new to the 'srcset' game so I'm not sure if there is a syntax error on my end. Keeping retina devices in mind, does anybody have an idea of what I'm missing here ? The browser support for srcset seems adequate so I'm not sure what could be causing this.

<img class="desktop-hero" alt="" src="../img/hero_desktop.jpg" srcset="../img/hero_mobile.jpg 768w, ../img/hero_desktop.jpg 1x" />

Solution

  • Edited to add: Yo, what tutorial did you get that markup from? I just realized that it looks like this is an attempt to use the old srcset syntax, which nobody ever implemented and which was a bad idea. If you can point out where you got it, we can try to get that tutorial to update, and prevent more people from making the same mistake.


    First, mixing w and x is invalid. That shouldn't be the immediate cause of your problems, but it will result in completely unpredictable behavior. (The w descriptor is converted into an equivalent x descriptor, based on its value and the value of the sizes attribute.)

    Second, the w descriptor doesn't do anything like what you're asking for. It's used, alongside the sizes attribute, as a way to specify the image's density indirectly, when the image's final size on the page is not a single hardcoded px value. It has nothing to do with the size of the screen, nor does it hide anything. It's the width of the image, in image pixels.

    Now, assuming that hero_desktop and hero_mobile are actually different images (different sizes, different crops, different content, etc), not just different-resolution versions of the same image, what you actually want to do is use <picture>:

    html:

    <picture>
      <source media="(min-width: 768px)" srcset="../img/hero_desktop.jpg">
      <img src="../img/hero_mobile.jpg">
    </picture>
    

    This will select the desktop image when the screen is >= 768px, and default to the mobile image otherwise.


    On the other hand, if the desktop and mobile images are the same image, just at different resolutions, then you do want to use <img srcset>, but stick with either x or w for both of them. Use x if the image is a static size, or it's allowed to be its "native" size. Use w (and sizes) if the image is set to a specific size by your layout. Then don't worry about when the image switches over; if you've declared things correctly, the browser will make a reasonable choice for you.