What srcset and sizes do
srcset gives the browser a list of versions of the same image with their real width
(800x450.jpg 800w). sizes tells it how wide the image will be on the page depending on the
screen size. With both, and knowing the screen’s pixel density, the browser picks the smallest file that still looks
sharp. It decides before laying out the page, which is why you have to tell it with sizes.
How to choose the widths
- Cover everything from mobile up to twice the maximum width the image takes, for high-density screens.
- Four to six widths are enough: more versions barely save bytes and complicate caching.
- Steps of around 300–400 px work well:
480, 800, 1200, 1600for an 800 px column.
img with srcset or picture
If only the size changes, <img srcset sizes> is enough. You need <picture> to offer
formats that not every browser understands: each <source> has a type and the browser
uses the first one it can read, so AVIF goes before WebP and the JPG in the <img> is the fallback.
It’s also used for “art direction”: different crops for different screens, with media.
Details people forget
widthandheight: with them the browser reserves the space before the image arrives and the page doesn’t jump (CLS). They just need the right aspect ratio.loading="lazy"on everything that isn’t visible on load. Never on the main image at the top: there it delays LCP.- The
altdescribes the image; if it’s decorative, it’s empty (alt=""), not missing.
The URLs in the code come from the ximg.es generator and each image has its width written on it, so you can paste the HTML into your layout and see at a glance which version loads on each screen. When you have the real photos, just swap the URLs.