Skip to content

Responsive Images

Lecture notes: the picture tag, the srcset attribute and optimizing graphics for different devices

HTML & CSS — Course for BeginnersLecture 18 of 192 min29 views

1. The picture tag

The <picture> tag lets you show different images on different devices. It is a wrapper (like <div>) that does not display anything itself.

Structure

HTML
<picture>
  <source
    srcset="banner-mobile.webp 1x, banner-mobile-2x.webp 2x"
    media="(max-width: 480px)"
  >
  <source
    srcset="banner-desktop.webp 1x, banner-desktop-2x.webp 2x"
  >
  <img src="banner-desktop.webp" alt="Banner">
</picture>

How it works

  • <source> — an equivalent of <img>, sets the image via srcset
  • The media attribute — the same media queries as in CSS (min-width, orientation, etc.)
  • The srcset attribute — a list of images with conditions (1x, 2x for pixel density or 320w, 768w for width)
  • <img> at the end — mandatory; needed for the alt attribute and as a fallback when loading fails

When to use it

  • Banners — a horizontal banner on desktop, a vertical one on mobile
  • Different formats — WebP for modern browsers, PNG/JPEG as a fallback
  • Different content — a detailed image on a large screen, a simplified one on a small screen

2. The srcset attribute

The srcset attribute can be used both in <source> and directly in <img>:

HTML
<img
  src="photo.jpg"
  srcset="photo.jpg 1x, photo-2x.jpg 2x, photo-3x.jpg 3x"
  alt="Photo"
>

Descriptors

  • 1x, 2x, 3x — pixel density (1x = a regular screen, 2x = Retina)
  • 320w, 768w — the image width in pixels (the browser picks the best one for the viewport width)

Caching specifics

The browser caches images and does not "downgrade" quality: if the 2x version has already been loaded, it will not load the 1x version when the window shrinks. For testing, enable Disable cache in DevTools.

SVG as a responsive image

You can write media queries inside an SVG file. The SVG elements will show or hide depending on the size. For example, a house icon: simplified on a small screen, and detailed (windows, doors) on a large one.

3. Summary table

TopicWhat to remember
<picture>Different images on different devices; <source> + media + srcset; <img> is mandatory
srcsetA list of images with descriptors: 1x/2x (density) or 320w/768w (width)

More interesting articles

Read the blog
01 / 06