Skip to content
GreenSnippets

Responsive images with srcset and the picture element

Serve modern formats and the right image size per device, with explicit dimensions to prevent layout shift.

HTML
<picture>
  <source type="image/avif" srcset="hero-480.avif 480w, hero-960.avif 960w" sizes="(min-width: 60rem) 50vw, 100vw" />
  <source type="image/webp" srcset="hero-480.webp 480w, hero-960.webp 960w" sizes="(min-width: 60rem) 50vw, 100vw" />
  <img
    src="hero-960.jpg"
    srcset="hero-480.jpg 480w, hero-960.jpg 960w"
    sizes="(min-width: 60rem) 50vw, 100vw"
    width="960"
    height="540"
    alt="A developer reviewing code on a laptop"
    loading="lazy"
    decoding="async"
  />
</picture>

How it works

<picture> lets the browser pick the first supported format (AVIF, then WebP, then JPEG fallback). srcset with sizes lets it pick the right width for the viewport. Always include width and height so the browser reserves space and avoids layout shift, and loading="lazy" for images below the fold (never for the main hero image).

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.