CodePark/ questions / Responsive design & units
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Responsive design & units

How do srcset, sizes and the picture element help with responsive images?

<img src="photo-800.jpg"
     srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
     sizes="(min-width: 60rem) 50vw, 100vw"
     alt="Harbour at sunset" width="800" height="533">

<picture>
  <source media="(min-width: 60rem)" srcset="wide.avif" type="image/avif">
  <img src="narrow.jpg" alt="Harbour at sunset">
</picture>

srcset lists several versions of an image, and the browser picks one. sizes tells the browser how wide the image will be shown. picture lets you force a specific choice.

srcset with w descriptors lists the same image at several widths, such as photo-400.jpg 400w. sizes tells the browser how wide the image will display at each breakpoint. The browser needs this because it chooses before the CSS loads. It combines that width with the screen's pixel density, then picks the smallest file that is good enough. Without sizes, it assumes 100vw, the full viewport width. For images with a fixed size, x descriptors (1x, 2x) are enough.

This is called resolution switching: the browser decides. Use picture with source elements when you must control the choice:

  • Art direction: a different crop on small screens, chosen with media.
  • Format fallback: AVIF or WebP chosen with type, with the inner img as the fallback.

The inner img is still required, and it carries the alt text.

Set width and height to reserve space, so the page doesn't jump when the image loads. That jump is called layout shift. Use loading="lazy" for images below the fold, which means images that are not visible until the user scrolls.

  • srcset lists candidate files, and sizes gives the displayed width.
  • The browser picks a file from the layout size and the screen's pixel density.
  • Use picture for art direction and format fallback.
  • Set width and height to prevent layout shift.