Responsive Images in HTML: w
and x
This article was prompted by a question from my friend Thomas about the Image plugin on the Eleventy Discord. This is a sort of a summary of the ensuing discussion, which was in itself something of a digression. For those not familiar with responsive images in HTML, I recommend MDN’s comprehensive guide, which also explains most of what’s covered here.
Thomas mentioned that he was at a loss to understand how w
and x
are equivalent
. I
clarified with the aid of an example that w
and sizes
are more capable and precise than x
(though vrugtehagel, creator of YOZO, pointed out
that the CSS must be written accordingly). Consider these two images:
<img width="400" height="200" srcset="foo-800.png 2x, foo-400.png">
<img width="400" height="200" srcset="foo-800.png 800w, foo-400.png 400w">
The first thing to remember is that width
and height
are advisory in modern browsers. Rather
than specifying absolute sizes, they’re used to infer aspect
ratios. How
much space the image actually takes up on the page (let’s call it the actual size) is usually
defined by the CSS. With that in mind, assuming foo-400.png is 400 pixels wide, consider the
browser’s selected image given these viewport widths, Device Pixel Ratios (DPRs), and actual
sizes on the page:
Viewport | DPR | Actual size | Selection (x ) |
Selection (w ) |
---|---|---|---|---|
400px | 1 | 400px | foo-400.png | foo-400.png |
400px | 2 | 400px | foo-800.png | foo-800.png |
800px | 1 | 800px | foo-400.png | foo-800.png |
200px | 2 | 200px | foo-800.png | foo-400.png |
With x
, the browser selects an image that’s too small in the third scenario and too big in the
fourth. With w
, it always selects the correct image. An important caveat, however, is that using
container queries with images renders sizes
less
useful, although the upcoming (I hope) sizes="auto"
can handle that given explicit
dimensions.
Nevertheless, an author who controls the images, markup, and CSS may find it easier to use
x
than to calculate the widths for w
, since the actual sizes are fixed. This is assuming a
particular image is only ever shown in one context. If the same image is shown at multiple actual
sizes, it could require treating the other sizes as additional DPR values or creating a copy
of the image with different multipliers.
vrugtehagel questioned why sizes
is required with w
and not x
. This is because using x
signals that only the density of the screen matters, meaning the actual size of the image is
irrelevant, and thus sizes
is redundant.
Finally, to Thomas’s original question, which we had forgotten altogether: the Image plugin does not
support the x
notation.