Picture Element for Art Direction

Uses the picture element with multiple sources to serve different images based on viewport size, format support, and pixel density.

HtmlFile Upload

Code

htmlsnippet
38 lines
<picture>
  <source
    media="(orientation: portrait)"
    srcset="tall-image-400.webp 400w,
            tall-image-800.webp 800w"
    sizes="100vw"
    type="image/webp">

  <source
    media="(min-width: 1200px)"
    srcset="wide-image-1200.webp 1200w,
            wide-image-1600.webp 1600w"
    sizes="80vw"
    type="image/webp">

  <source
    media="(min-width: 600px)"
    srcset="medium-image-600.webp 600w,
            medium-image-900.webp 900w"
    sizes="90vw"
    type="image/webp">

  <source
    srcset="small-image-400.webp 400w"
    type="image/webp">

  <source
    media="(min-width: 1200px)"
    srcset="wide-image-1200.jpg 1200w"
    sizes="80vw"
    type="image/jpeg">

  <img src="fallback-image.jpg"
       alt="Hero banner showing the product"
       loading="eager"
       width="1200"
       height="600">
</picture>

The <picture> element evaluates <source> elements in order, picking the first match based on media and type. This enables art direction (different crops for different screens), format negotiation (WebP/AVIF with JPEG fallback), and responsive sizing. The <img> element is the fallback and provides alt text. Sources are evaluated top-to-bottom; first match wins.