How to serve responsive images with srcset and sizes attributes
srcset width descriptors, sizes attribute, pixel density descriptors, art direction, picture element, viewport-relative sizes, image CDN resizing
Responsive Images with srcset
Serving a 2400px image to a 375px mobile screen wastes 95% of the bytes. srcset and sizes give the browser the information it needs to pick the right image for the current viewport and pixel density.
<img
src="hero-800.jpg"
srcset="hero-400.jpg 400w,
hero-800.jpg 800w,
hero-1200.jpg 1200w,
hero-2400.jpg 2400w"
sizes="(max-width: 600px) 100vw,
(max-width: 1200px) 50vw,
800px"
alt="Hero image"
width="800"
height="450"
>How this works: srcset lists available image files with their intrinsic widths. sizes tells the browser how wide the image will be rendered at each viewport width. The browser multiplies the rendered size by the device pixel ratio and picks the smallest srcset entry that covers it.
For a 375px phone with 2× DPR, the browser needs a 750px image. It picks hero-800.jpg (smallest that covers 750px).
Art direction — serving a different crop on mobile — requires <picture>:
<picture>
<source media="(max-width: 600px)" srcset="hero-square.webp">
<img src="hero-wide.webp" alt="Hero">
</picture>Image CDNs (Cloudinary, imgix, Cloudflare Images) generate all size variants on-demand from a single master file, eliminating manual conversion.
