Saltar al contenido principal
← 📄 HTML & the platform·Módulo A4 · Lección 6
TareaBuild 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.

<imagen> + srcset: imágenes responsivas

125 XP10 min
Teoría

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

Regístrate para empezar a programar

La teoría está abierta a todos. El editor, la vista previa y el check se desbloquean con una prueba gratis de 7 días — se requiere tarjeta, cancela cuando quieras.

Registrarse — prueba gratis →

Las primeras 10 lecciones de cada ruta son gratis. No se necesita tarjeta.

← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.