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
- GreenSnippets
- MIT
<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.
Related snippets
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- Bash
Run commands in parallel with xargs
Process many files concurrently with xargs -P, safely handling spaces and newlines in names.

