Přejít k hlavnímu obsahu
← 📄 HTML & the platform·Modul A4 · Lekce 6
ÚkolBuild 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.

<obrázek> + srcset: responzivní obrázky

125 XP10 min
Teorie

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>.
🔒

Zaregistruj se a začni programovat

Teorie je otevřená pro každého. Editor, živý náhled a check se odemknou s 7denní zkušební verzí zdarma — karta vyžadována, zrušíš kdykoli.

Registrace — zkušební verze zdarma →

Prvních 10 lekcí v každé trase je zdarma. Karta není potřeba.

← PředchozíDalší lekce →

Jeden tip k Pythonu nebo webu denně — e-mailem

Krátké, ručně psané, žádný spam. Odhlásit jedním klikem.