CPCODELAB
HTML

Responsive Images with picture and srcset

9 min read

Beyond the Basic img Tag

A single <img> loads the same file on every device. On a phone, that wastes bandwidth; on a high-DPI screen, it looks blurry. The <picture> element and the srcset attribute solve both problems by letting the browser choose the best source.

srcset for Resolution Switching

html
<!-- Browser picks the best size based on the viewport -->
<img
  src="/images/hero-800.jpg"
  srcset="
    /images/hero-400.jpg  400w,
    /images/hero-800.jpg  800w,
    /images/hero-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 100vw, 50vw"
  alt="Mountain landscape at golden hour"
  width="800"
  height="450"
/>

picture for Art Direction

Use <picture> when you want to serve a completely different image at different breakpoints — for example, a wide landscape on desktop and a tight portrait crop on mobile.

html
<picture>
  <!-- WebP for modern browsers -->
  <source
    type="image/webp"
    srcset="/images/hero.webp"
  />
  <!-- AVIF for browsers that support it -->
  <source
    type="image/avif"
    srcset="/images/hero.avif"
  />
  <!-- Art direction: different crop on small screens -->
  <source
    media="(max-width: 600px)"
    srcset="/images/hero-portrait.jpg"
  />
  <!-- Fallback img is always required -->
  <img
    src="/images/hero.jpg"
    alt="Mountain landscape at golden hour"
    width="1200"
    height="675"
  />
</picture>

The <img> inside <picture> is always required — it is the fallback and also the element that carries alt, width, and height. Browsers that do not support <picture> simply display the <img>.

  • srcset with w descriptors — lets the browser choose based on layout width and screen density.
  • sizes — tells the browser how wide the image will be rendered at various breakpoints.
  • <picture> + <source media> — swap entire images for art direction.
  • <picture> + <source type> — serve next-gen formats (WebP, AVIF) with a JPEG fallback.
Ready to test yourself?
Practice HTML— quiz & coding exercises