Skip to main content
← πŸ“„ HTML & the platformΒ·Module A4 Β· Lesson 6
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>

  1. 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.
  2. 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" />
  • srcset lists each file with its intrinsic width.
  • sizes tells 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 β†’ srcset on <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.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.