Firefox: Img with 2x srcset specified has weird spacing when inside float

419 views Asked by At

I have HTML like so:

<div id='container'>
  <div class='left mr1'>
    <img src='https://placehold.it/100x50' srcset='https://placehold.it/200x100 2x'>
  </div>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

CSS like so:

#container {
  width: 400px;
  background: #eee;
  padding: 10px;
}

.mr1 {
  margin-right: 10px;
}

.left {
  float: left;
}

In Firefox only, when viewed on a "retina" display, this results in the .left div (which has no width specified) having double width. I cannot replicate this on any other browser.

Screenshot:

screenshot

Recreated in this pen.

1

There are 1 answers

0
Jeremy John On

I can confirm the bug.

Here is the simplest solution. This sets the max width on all images to their natural width, which, it turns out, is the correct size. But this means no images can stretch past their natural width on your site, which you may want. That is to say, this following must be used with caution and will override any max-width declaration on images on your site.

  $('html').imagesLoaded(function() {
    $('img').each(function() {
      // Exclude SVG images.
      if (this.src.split('.').pop().toLowerCase() !== 'svg') {
        var imgWidth = this.naturalWidth;
        $(this).css('max-width', imgWidth); // Set max width of element to the natural width of the img specified in the src tag. This means that srcset images cannot swell size the image as in FF.
      }
    });
  });

You're going to need the imagesLoaded plugin because the size of img elements is not known until after they load.

Note, I am using jQuery here. But this could easily be achieved with vanilla JS.