Note to self—preventing images from triggering 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:
max-width: 100%so it doesn't overflow the available spacewidth: (image.naturalWidth)pxso it doesn't exceed its actual widthaspect-ratio: width / heightso it keeps the right aspect ratio
If you're height-constrained then just set the max-height and height
instead.
Note that if you set both
widthandheightthemax-widthsquashes the image, and if you useobject-fitit 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.