DEV Community

Michael Vestergaard
Michael Vestergaard

Posted on

Responsive image with different aspect ratios

I recently discovered a small browser bug (or at least undesired behavior) related to the picture tag.

It's quite normal in many designs to use taller mobile images and wider desktop images. This means we have different aspect ratios. As freelance developer I often run into designs that use different aspect ratios between mobile and desktop layouts.

When crossing the breakpoint and going from one image to the other, the image size isn't instantly set correct, it doesn't happen until the image has loaded (tested in Chrome). This is problematic because we might have elements further down the page trying to read offsetTop or similar - this reading will be wrong until the image has loaded. You would think that setting the width and height on the "img" and "source" tag would solve this, but it doesn't.

I made this little demo to show the problem. In the console logs it's obvious that the readings are wrong. You can also see the fix:

The solution is fairly simple: Instead of relying only on the normal "resize" event, use a ResizeObserver to check for changes in the document height.

I'm pretty sure the reason for this behaviour, is to always show an image. So while the new image loads the browser keeps showing the old image. This is good (looking) for many reasons, but of course gives us the false readings mentioned above.

Top comments (0)