3 ms·
> How to avoid layout shifts caused by images. And it’s funny how the state of the art way to address these issues is usually some absurd hack. Like in the cas
by dmitryminkovsky 5y ago
> How to avoid layout shifts caused by images.
And it’s funny how the state of the art way to address these issues is usually some absurd hack. Like in the case of images, setting the height to 0 and using padding to achieve a stable height: https://nikitahl.com/css-aspect-ratio https://nikitahl.com/css-aspect-ratio.
- megous 5y agoNormal way to achieve img to have a size before the resource in src loads is to set width/height attributes to the native size of the resource that will be loaded (because you have to tell the browser size of an image somehow), and if you want to scale it with aspect ratio preserved you just use min/max-width/height in css to fit it to whatever size you need.
- dmitryminkovsky 5y agoYou’d think, right? But I tried that approach, and I don’t remember what the issues were but there were problems. Unless I was doing something wrong. Either way, yes, you need the dimensions ahead of time, which is reasonable and not my gripe.
- lelandfe 5y ago> Unless I was doing something wrong Probably this, that approach is very standardized now across the major browsers. I worked at a web agency until last year, and led projects to inline image height/width values for 4 large companies. Huge reduction in CLS and permits you to lazyload without fear of layout shifts. `aspect-ratio` hadn't landed in iOS Safari at that point, but you can do that instead now. Identical behavior.
- megous 5y agoWell, if you set max-width: something for example. You need to set other dimension as auto in CSS. So that would be height: auto.
- esprehn 5y agoThe aspect ratio hack was replaced by the aspect-ratio CSS property: https://web.dev/aspect-ratio/ https://web.dev/aspect-ratio/ Which is supported in all modern browsers: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-rati... The state of the art for CSS these days is not that hacky.
- dmitryminkovsky 5y agoCool I didn't know this. Thank you.