The WHATWG (Web Hypertext Application Technology Working Group) has updated the HTML standard to include
sizes="auto" to responsive images. This does not mean any browser is necessarily working on it yet, let alone on the cusp of shipping it, but I think and hope that it will become part of our everyday syntax. It will greatly simplify providing the right size native image for the target display size and resolution.
How we do it now
To give browsers the info they need to download the correctly sized image, we have to provide them with what size images are available and when to use each of them, based on viewport size. The first part, the what, is specified in the
srcset attribute of the image; the when is specified in the
Here’s an example:
Embedded content: https://gist.github.com/ostermanj/5e7b56d6a62e60bc0d3d9ed5c9e00689
See MDM for a fuller description.
sizes attribute tells the browser how big the display size of the image will be at different viewport widths. You can specify absolute pixel sizes or relative viewport units, which is nice. But you have to do the calculations and tell the browser which image to download before it’s calculated the page layout so that image will be ready to display when layout is ready.
This method is a major limitation if you are using reusable components that will render on the page at sizes that are unknown to you at development time. There’s no way to tell the browser which image to download based on container size because it is not knowable until layout is calculated.
Lazy load to the rescue
When you use
loading="lazy"—and you should be for many if not most of your images—the browser does know what the page layout and display size of the image is before it has to download the file. The browser has to calculate whether the image is in or nearing the viewport before lazily loading it. In this case, there ought to be no reason you have to tell the browser which images to download based on screen size—it already knows! That’s where
sizes="auto" comes in. It tells the browser to figure out by itself which image from the
srcset to use. As it does now, the browser will take the screen resolution into account when making that decision, so you’ll automatically get the sharpest image available for the given display size.
So when can I use it?
Dunno. It was just merged into the spec in early June 2023, and major browsers have expressed interest. I’m hoping for ASAP. I plan on using it as soon as I can.