TaskBuild a <picture> that loads /hero-mobile.webp on screens up to 600px wide, /hero-desktop.webp on larger screens (both WebP), and falls back to /hero.jpg.
<picture> + srcset: responsive images
125 XP10 min
Theory
Same image, multiple sizes β browser picks the best
<picture> <source media="(max-width: 600px)" srcset="/hero-mobile.webp" type="image/webp" /> <source srcset="/hero-desktop.webp" type="image/webp" /> <img src="/hero-desktop.jpg" alt="Hero" width="1200" height="630" /> </picture>
The browser walks <source> tags top-to-bottom; the first match wins. Falls through to the <img> if nothing matches (and as the fallback for browsers that don't understand WebP).
Two reasons to use <picture>
- Art direction β show different CROPS on different screens (a horizontal photo on desktop, a vertical one on mobile). One image src can't do this.
- Format fallback β prefer WebP / AVIF for browsers that support them, fall back to JPG/PNG.
srcset on a plain <img> (no <picture>)
For "same image, different DPRs" (Retina vs non-Retina), just use srcset directly:
<img src="/hero.jpg"
srcset="/hero.jpg 1x, /hero@2x.jpg 2x, /hero@3x.jpg 3x"
alt="Hero" />Or for fluid widths:
<img src="/hero-400.jpg"
srcset="/hero-400.jpg 400w, /hero-800.jpg 800w, /hero-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Hero" />srcsetlists each file with its intrinsic width.sizestells the browser how wide the image will display at different viewport sizes.- The browser picks the smallest file that's still large enough for the calculated display width Γ DPR.
When to use <picture> vs srcset
- Same crop, different sizes β
srcseton<img>. - Different crops or different formats β
<picture>with<source>.
π
Sign up to start coding
Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β card required, cancel anytime.
Sign up β free trial βFirst 10 lessons in each track are free. No card needed for those.