patternjavascriptModerate
Responsive images with srcset and sizes to avoid oversized downloads
Viewed 0 times
srcsetsizesresponsive imagesimage optimizationbandwidthDPRpicture element
Problem
Serving a 2400px wide image to a mobile device with a 375px viewport wastes 10-20x the bandwidth. The image looks identical to the user but causes a much larger download.
Solution
Use the srcset attribute to provide multiple image sizes and the sizes attribute to tell the browser which to pick.
<img
src="/photo-800.webp"
srcset="
/photo-400.webp 400w,
/photo-800.webp 800w,
/photo-1200.webp 1200w,
/photo-2400.webp 2400w
"
sizes="
(max-width: 640px) 100vw,
(max-width: 1024px) 50vw,
33vw
"
alt="Photo"
width="800"
height="600"
/>
<img
src="/photo-800.webp"
srcset="
/photo-400.webp 400w,
/photo-800.webp 800w,
/photo-1200.webp 1200w,
/photo-2400.webp 2400w
"
sizes="
(max-width: 640px) 100vw,
(max-width: 1024px) 50vw,
33vw
"
alt="Photo"
width="800"
height="600"
/>
Why
The browser evaluates sizes against the current viewport, selects the appropriate source from srcset, and accounts for device pixel ratio. A 375px viewport with 2x DPR fetches the 800w source — not the 2400w one.
Gotchas
- srcset with w descriptors requires the sizes attribute — without it the browser defaults to 100vw
- sizes is evaluated at parse time — it cannot use CSS custom properties or calc() with dynamic values
- Generate image variants at build time with sharp, imagemin, or a CDN image transformation API
- art direction (different crops at different breakpoints) requires the <picture> element with <source media> tags, not srcset alone
Code Snippets
Picture element for art direction with WebP sources
<!-- Art direction: different crops for mobile vs desktop -->
<picture>
<source
media="(max-width: 640px)"
srcset="/photo-portrait-400.webp 400w, /photo-portrait-800.webp 800w"
sizes="100vw"
/>
<img
src="/photo-landscape-800.webp"
srcset="/photo-landscape-800.webp 800w, /photo-landscape-1600.webp 1600w"
sizes="50vw"
alt="Photo"
width="800"
height="600"
/>
</picture>Context
When serving images that need to adapt to different viewport sizes and device pixel ratios
Revisions (0)
No revisions yet.