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: srcset with w descriptors and sizes lets the browser pick the right image file

Web-Development
~/tips/tip-img-srcset-sizes-width

srcset="photo-400.jpg 400w,

Phones download a small file and large screens a sharp one, from one img tag.

Sending a 2000 pixel photo to a phone wastes data, but a small file looks blurry on a big screen. With srcset I’d list the files you have and let the browser choose.

<img src="photo-800.jpg"
     srcset="photo-400.jpg 400w,
             photo-800.jpg 800w,
             photo-1600.jpg 1600w"
     sizes="(min-width: 50rem) 50rem, 100vw"
     width="1600" height="1067" alt="A canal in autumn">

Each entry in srcset is a file plus its real width in pixels, written with a w. sizes tells the browser how wide the image will be shown: here 50rem once the screen is at least 50rem wide, otherwise the full viewport width. The browser combines that with the screen’s pixel density and downloads the smallest file that is sharp enough. src stays as the fallback.

The sizes value is the part people get wrong. Without it the browser assumes 100vw, so a thumbnail in a three column grid still gets a full width file. Make it match your CSS.

The browser is free to choose, so it may take a larger file it already has cached. That is by design. For lazy loaded images there is now sizes="auto", which uses the real layout width, but MDN shows it only in Chrome 126 and Firefox 150 with partial support in Safari 27, so keep a real value next to it for now.

Further reading: MDN: Responsive images, MDN: HTMLImageElement.sizes

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