Images and media

The picture element

Use picture when the image composition or file format should change under specific conditions while keeping a dependable img fallback.

Use picture when you need art direction: a different crop or composition for a different layout.

<picture>
  <source
    media="(max-width: 600px)"
    srcset="harbor-close-up.jpg"
  >
  <img
    src="harbor-wide.jpg"
    alt="Cyclists crossing the harbor bridge"
    width="1200"
    height="700"
  >
</picture>

On a small screen, the close crop keeps the cyclists visible. On a wider screen, the fallback img shows the full scene.

The browser reads source elements from top to bottom and uses the first matching one. The img element is required. It provides the fallback, alt text, dimensions, and other image behavior.

picture can also offer newer file formats:

<picture>
  <source srcset="harbor.avif" type="image/avif">
  <source srcset="harbor.webp" type="image/webp">
  <img src="harbor.jpg" alt="Cyclists beside the harbor">
</picture>

If you only need smaller and larger copies of the same composition, img with srcset is simpler.

Do not put alt on source. It belongs on the inner img. That one element carries the accessible name no matter which source matched.

For format switching, order matters: list the most efficient format first, then fall back to JPEG or PNG on the img. Browsers that lack AVIF support skip that source and try the next one.

Art direction is for when cropping changes the story, not just the pixel count. A portrait crop on mobile and a landscape crop on desktop is a good fit. Three JPEG widths of the same frame is still a job for srcset on a plain img.

You can combine both patterns: source elements inside picture for format or media queries, with srcset on each source when you need multiple widths for that variant. Start simple first. Add complexity only when a real layout needs it.

Test with DevTools device mode. Resize across the breakpoint in your media attribute and confirm the image swap matches what you expect.

Quick check

Result

You got of right.

Lesson completed