brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: width and height on every img stop the page from jumping while images load

Web-Development
~/tips/tip-img-width-height-no-layout-shift

alt="Boats in the harbour at sunset">

The browser reserves the right space for an image before the file arrives.

Text that jumps down while I am reading, because an image above it just loaded, is one of my pet peeves. The fix is two old attributes that responsive design made people drop.

<img src="harbour.jpg" width="1600" height="900"
     alt="Boats in the harbour at sunset">

img {
  max-width: 100%;
  height: auto;
}

Current browsers use width and height to compute an aspect ratio before the image has loaded. With the CSS above, the image scales to the width of its column, and the browser already knows it will be 9/16 of that width tall. The space is reserved, so nothing below it moves when the pixels arrive.

The numbers do not need to be the size you display. They only need the right ratio, so the real pixel size of the file is the easiest choice. Without the attributes the browser assumes zero height until the image loads, which is exactly what causes the jump and hurts your layout shift score.

MDN lists support for this ratio mapping in Chrome 79, Firefox 71 and Safari 15.

The caveat is height: auto in CSS. If a stylesheet sets a fixed height and leaves width flexible, the image gets stretched. And when the file’s real ratio differs from the attributes, the browser switches to the real ratio once it loads, so the jump comes back in a smaller form.

Further reading: MDN: img element, MDN: aspect-ratio

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link