Lesson 30 +10 XP

Responsive Images

Responsive Images

Different screens need different pictures. A huge photo wastes data on a tiny phone; a tiny photo looks blurry on a big TV. Responsive images fix this!

The problem

  • Phone: small screen, small image, less data.
  • Laptop: medium image.
  • TV: huge, sharp image.

Solution 1: srcset with sizes

srcset lists several image versions with their widths. The sizes attribute tells the browser how big the image will be on screen. The browser picks the best one.

<img
  src="cat-480.jpg"
  srcset="cat-480.jpg 480w, cat-960.jpg 960w, cat-1920.jpg 1920w"
  sizes="(max-width: 600px) 100vw, 50vw"
  alt="A cute cat">

The w means "width in pixels" of the image file.

Solution 2: the <picture> element

When you want to show a COMPLETELY different image (different crop, or a different format), use <picture>.

<picture>
  <source media="(min-width: 800px)" srcset="landscape.jpg">
  <source type="image/webp" srcset="photo.webp">
  <img src="photo.jpg" alt="A mountain view">
</picture>
  • media: a screen-size condition.
  • type: an image format condition (like WebP vs JPEG).
  • The <img> at the end is the fallback: always include it!

Why bother?

  • Faster pages on phones (less data).
  • Sharp images on big screens.
  • Better formats (WebP, AVIF) when supported.

TL;DR

  • srcset + sizes → browser picks the best size.
  • <picture> + <source> → different image per condition.
  • Always keep the <img> as the fallback.
  • Result: fast AND sharp images everywhere.