Note to self—preventing images from triggering layout shifts

avoiding layout shifts

It took me a minute to figure this out, so I think it's worth a quick note to my future self and who knows, it may save someone a minute or two one day.

The question is, how to set an image's size so that it displays at the largest size that makes sense, but doesn't trigger a refresh when it loads.

Assuming you're width constrained, the answer I came up with is:

If you're height-constrained then just set the max-height and height instead.

Note that if you set both width and height the max-width squashes the image, and if you use object-fit it ends up cropped or with empty "bars".

The way this works in my blog editor is that when it generates markdown it also goes through all the <img> elements in the wysiwyg editor and if they're loaded it sets the attributes of the element.

It's simple and it works, and now I'm not getting dinged by Lighthouse for layout shifts.

— Tonio Loewald,