Skip to main content

Frontend development · Intermediate · 28 min

Serve responsive images with srcset and picture

By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard · sharp-cli 6.1.0 · checked in Chromium with Playwright 1.65.1

You will have a clinic web page whose photos come in several widths and in AVIF, WebP and JPEG, with a closer crop of the entrance on phones, lazy loading below the fold and space held for every image, plus a script that reports which file each screen size downloads.

On this page

A photo on a web page is usually the heaviest thing it downloads. If you export one large JPEG and let CSS shrink it, a phone that shows the photo 328 pixels wide still pays for every pixel of a 1,920-pixel file. HTML can do better on its own: srcset and sizes let the browser pick a file that fits the screen, and <picture> lets you offer newer formats and a different crop where the layout needs one.

You will build the "Visit us" page for Larkfield Clinic, the fictional community clinic used across the design tutorials on this site. It holds the three photos from the photo sheet in Choose and crop photos for an interface: the front entrance at the top, then the reception desk and a nurse's consulting room further down. The sheet places them on different pages of the clinic website; this demo brings them together on one page so you can compare how each is served. You will generate every size and format with a command-line tool, write the markup in stages, and check each one with a short Playwright script that loads the page as a phone, a tablet and a desktop and lists the image files each one requested.

This tutorial covers every image on a page. Making the top image arrive as early as possible is a separate job, covered in Improve Largest Contentful Paint.

Step 1 · Set up the project

Make a folder for the demo and install two tools, pinned to exact versions so your output matches this page. sharp-cli is a command-line front end for sharp, an image library built on libvips that reads and writes JPEG, PNG, WebP and AVIF. Playwright drives a real browser from a script, which the report in step 5 needs:

Bash
mkdir -p ~/responsive-images-demo/originals ~/responsive-images-demo/site
cd ~/responsive-images-demo
npm init -y > /dev/null
npm install --save-dev --save-exact sharp-cli@6.1.0 playwright@1.65.1
npx playwright install --with-deps chromium

The last command downloads the Chromium build that this Playwright version drives. On Linux, --with-deps also installs the system libraries Chromium needs, using sudo, so it may ask for your password. On macOS it only downloads the browser.

Check it worked

Both tools print their versions:

Bash
cd ~/responsive-images-demo
npx sharp --version
npx playwright --version

The output is 6.1.0, then Version 1.65.1.

Step 2 · Prepare the source photos

Start from the largest, least-compressed copy of each photo you have, such as the camera original or a full-size export from your design tool. Every smaller file is made from it, and you cannot add back detail that an earlier export threw away. Keep originals out of the folder you publish: they are for making files, not for serving.

Larkfield needs three: entrance.jpg, reception.jpg and nurse.jpg. If you are following along without real photos, make stand-ins. sharp renders SVG, so you can draw a simple scene with a soft texture over it and save it as a 2,400 by 1,600 pixel JPEG. The texture matters: flat colour compresses to almost nothing, which would hide the differences between formats.

Bash
cd ~/responsive-images-demo
cat > originals/entrance.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" width="2400" height="1600" viewBox="0 0 2400 1600">
  <filter id="grain">
    <feTurbulence type="fractalNoise" baseFrequency="0.015" numOctaves="5" seed="4"/>
    <feColorMatrix values="0 0 0 0 0.5  0 0 0 0 0.5  0 0 0 0 0.5  0 0 0 0.35 0"/>
    <feBlend in="SourceGraphic" mode="multiply"/>
  </filter>
  <g filter="url(#grain)">
    <rect width="2400" height="1600" fill="#b9d3e6"/>
    <rect y="380" width="2400" height="1020" fill="#d8cbb4"/>
    <rect x="200" y="560" width="520" height="380" fill="#8fb1c4"/>
    <rect x="1880" y="560" width="400" height="380" fill="#8fb1c4"/>
    <rect x="1180" y="440" width="360" height="90" fill="#ffffff"/>
    <rect x="1080" y="560" width="560" height="840" fill="#0f5e5a"/>
    <rect x="1140" y="620" width="440" height="780" fill="#2a3b44"/>
    <polygon points="300,1400 1080,1240 1080,1400" fill="#a9a39a"/>
    <rect y="1400" width="2400" height="200" fill="#77736d"/>
  </g>
</svg>
SVG
cat > originals/room.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" viewBox="0 0 1800 1200">
  <filter id="grain">
    <feTurbulence type="fractalNoise" baseFrequency="0.02" numOctaves="5" seed="9"/>
    <feColorMatrix values="0 0 0 0 0.5  0 0 0 0 0.5  0 0 0 0 0.5  0 0 0 0.35 0"/>
    <feBlend in="SourceGraphic" mode="multiply"/>
  </filter>
  <g filter="url(#grain)">
    <rect width="1800" height="1200" fill="#e3f0ee"/>
    <rect y="860" width="1800" height="340" fill="#c9c2b6"/>
    <rect x="160" y="200" width="560" height="420" fill="#ffffff"/>
    <rect x="980" y="640" width="200" height="220" fill="#0f5e5a"/>
    <rect x="1240" y="640" width="200" height="220" fill="#0f5e5a"/>
    <rect x="1500" y="640" width="200" height="220" fill="#0f5e5a"/>
  </g>
</svg>
SVG
npx sharp -i originals/entrance.svg -o originals/entrance.jpg -f jpeg -q 90
npx sharp -i originals/room.svg -o originals/reception.jpg -f jpeg -q 90
npx sharp -i originals/room.svg -o originals/nurse.jpg -f jpeg -q 90 flop

The entrance stand-in has a sky, a wall with two windows, a white sign over a green door, and a ramp rising to the left of the door. flop mirrors the room drawing so the two interior stand-ins differ.

With real photos, check two things before you go on. If a phone photo appears rotated in the browser, add --autoOrient to every npx sharp command in the next steps, so the camera's orientation tag is applied to the pixels. And sharp leaves out EXIF metadata such as GPS location unless you ask for it with --metadata, which is what you want for photos of a building and its staff.

Check it worked

List the folder:

Bash
cd ~/responsive-images-demo
ls -l originals

You see entrance.jpg, reception.jpg and nurse.jpg next to the two SVG files. Open entrance.jpg in an image viewer: it is a textured drawing of a building front with a green door in the middle and a grey ramp on its left.

Step 3 · Work out the widths from the layout

A browser picks an image file before it has laid out the page, so it cannot measure how wide the image will be. You tell it, and the answer comes from your CSS. Write the stylesheet first:

Bash
cd ~/responsive-images-demo
cat > site/style.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; color: #1b1f24; background: #f6f7f8; }
main { max-width: 60rem; margin: 0 auto; padding: 1rem; }
img { display: block; max-width: 100%; height: auto; }
figure { margin: 0 0 1.5rem; }
figcaption { margin-top: 0.5rem; font-size: 0.875rem; color: #5a6270; }
.gallery { display: grid; gap: 1rem; }
@media (min-width: 37.5rem) {
  .gallery { grid-template-columns: 1fr 1fr; }
}
CSS

img { max-width: 100%; height: auto; } lets every image shrink to its container and keep its shape. The content column is at most 60rem (960 pixels) including 1rem of padding on each side. From that, read off how wide each photo is shown:

  • The entrance photo fills the column. Below a 960-pixel window it is the window width minus 32 pixels of padding, which CSS writes as calc(100vw - 2rem). From 960 pixels up it stops growing at 58rem, which is 928 pixels.
  • The reception and nurse photos sit in the gallery: one column on narrow screens, the same width as the entrance; two columns from 37.5rem (600 pixels), each half the column minus half the 1rem gap, calc(50vw - 1.5rem); and a fixed 28.5rem (456 pixels) from 960 pixels up.

Now multiply by screen density. A budget Android phone that is 720 physical pixels wide usually reports 360 CSS pixels at a density of 2, so the entrance shows 328 CSS pixels wide but needs a 656-pixel file to look sharp. A laptop at density 1 shows the same photo 928 wide and needs 928 pixels. Pick file widths that cover that range in steps, without making so many that the gaps are tiny. For Larkfield:

  • Entrance, desktop crop (21:9): 960, 1280 and 1600 pixels. 1600 is the largest export the photo sheet budgets for.
  • Entrance, phone crop (16:9): 480, 720 and 960 pixels.
  • Reception and nurse (3:2): 480, 720 and 960 pixels. The 720 file is for the phone at density 2, which needs 656 pixels; without it the browser has to choose between a file that is too small and one that is far too large.

The phone crop is a different shape because a 21:9 strip at 328 pixels wide is only 141 pixels tall, too short to make out the door and the sign. Step 7 uses it.

The photo sheet also gives reception a 4:5 phone crop and the nurse a 1:1 one. This demo keeps their 3:2 desktop crop on phones as well: they are supporting photos lower down the page, where a wide frame still shows the desk and the two faces, and art direction is shown once, on the entrance photo. On your own pages, build their phone crops the same way step 7 builds the entrance's.

Check it worked

Do the sum for one more screen to test the list: a 768-pixel-wide tablet at density 1. The entrance is shown at 768 − 32 = 736 pixels, so the browser needs at least 736 pixels and the 960 file is the first one wide enough. Each gallery photo is shown at 768 ÷ 2 − 24 = 360 pixels, so the 480 file covers it. If a screen size you care about lands far above the largest file, add a width; if two files are less than about 20 percent apart, drop one.

Step 4 · Generate every width and format

Put the export rules in one script, so you can re-run it whenever a photo changes. For each crop and width it writes three files: AVIF, the smallest; WebP, a little larger; and JPEG for browsers that support neither. The quality values are starting points. Compare the results by eye at full size and adjust them for your photos.

Bash
cd ~/responsive-images-demo
cat > make-images.sh <<'SH'
#!/usr/bin/env bash
# Writes every width and format the page needs into site/img.
set -euo pipefail
cd "$(dirname "$0")"

# encode <source> <output name> <sharp commands...>
encode() {
  local src=$1 out=$2
  shift 2
  npx sharp -i "$src" -o "site/img/$out.avif" -f avif -q 50 "$@" > /dev/null
  npx sharp -i "$src" -o "site/img/$out.webp" -f webp -q 75 "$@" > /dev/null
  npx sharp -i "$src" -o "site/img/$out.jpg" -f jpeg -q 75 "$@" > /dev/null
  echo "wrote site/img/$out (avif, webp, jpg)"
}

# P1 entrance, desktop crop: 21:9, the whole front of the building
for w in 960 1280 1600; do
  encode originals/entrance.jpg "entrance-wide-$w" extract 410 24 2352 1008 -- resize "$w"
done

# P1 entrance, phone crop: 16:9, closer in on the sign, door and ramp
for w in 480 720 960; do
  encode originals/entrance.jpg "entrance-phone-$w" extract 430 340 1760 990 -- resize "$w"
done

# P2 reception and P3 nurse: 3:2 on every screen in this demo
for name in reception nurse; do
  for w in 480 720 960; do
    encode "originals/$name.jpg" "$name-$w" resize "$w"
  done
done
SH
chmod +x make-images.sh
./make-images.sh

The extract command takes the top, left, width and height of the area to keep, in pixels of the original, and -- chains the next command, so each crop is cut first and then resized. The two crop boxes come from the safe area you marked in the photo sheet: for your own photos, read the box positions off your design file.

The script runs npx sharp 36 times and takes a little while. A build tool or an image CDN does the same job at scale, but the inputs are the same decisions: which crops, which widths, which formats.

Check it worked

Count the files and compare the formats for one size:

Bash
cd ~/responsive-images-demo
ls site/img | wc -l
ls -l site/img/entrance-wide-960.*

The count is 36. Of the three entrance-wide-960 files, the AVIF is the smallest and the JPEG the largest, usually by a wide margin, though the exact ratio depends on the photo and the quality settings. Real photographs have more detail than these stand-ins, so all three files will be larger, but the order is usually the same. Open site/img/entrance-phone-720.jpg and site/img/entrance-wide-960.jpg side by side: the phone crop is closer, with the sign, the door and most of the ramp filling the frame.

Step 5 · Write srcset and sizes

Start with the entrance photo alone, in one format, so the choice of width is all you are testing. Create a first stage page:

Bash
cd ~/responsive-images-demo
cat > site/srcset.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Stage 1: srcset and sizes</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<main>
  <h1>Visit Larkfield Clinic</h1>
  <img src="img/entrance-wide-960.jpg"
       srcset="img/entrance-wide-960.jpg 960w,
               img/entrance-wide-1280.jpg 1280w,
               img/entrance-wide-1600.jpg 1600w"
       sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)"
       width="1600" height="686"
       alt="The front entrance of Larkfield Clinic, with a ramp to the left of the door.">
</main>
</body>
</html>
HTML

Read the attributes in this order:

  • srcset lists the candidate files, each with a w descriptor: the file's real width in pixels. It is a menu, not an instruction.
  • sizes says how wide the image will be shown, as a list of media conditions and lengths. The browser takes the first condition that matches and uses the last entry, which has no condition, when none do. These are the two widths you worked out in step 3.
  • The browser divides each file's width by the display width to get its density, compares that with the screen's density, and picks a file. It does not always take the first file that is dense enough: when a file slightly below the screen's density is much closer than the next one up, Chromium may choose it, and that is what you will see in developer tools. The HTML standard leaves the final choice to the browser, so it may prefer a file it already has in its cache, or a smaller one when data saving is on.
  • src is the fallback for browsers that ignore srcset, and the default the others start from.
  • width and height give the image's shape before any file arrives. Step 8 shows why that matters.

sizes is the part people get wrong. If it says 100vw but the photo sits in a narrow column, every screen downloads a file several times larger than it shows.

Now the report. This script opens a page in Chromium at three screen sizes: a 360-pixel phone at density 2, a 768-pixel tablet and a 1280-pixel laptop at density 1. It records each image request, scrolls to the bottom, and prints what was downloaded and when. It serves the site folder through Playwright's request routing, so you do not need a web server:

Bash
cd ~/responsive-images-demo
cat > report.mjs <<'JS'
// Usage: node report.mjs [page]
// Lists the image files a phone, a tablet and a laptop download for one page in site/.
import { chromium } from 'playwright'
import { statSync } from 'node:fs'
import { join, basename } from 'node:path'

const file = process.argv[2] ?? 'index.html'
const site = join(import.meta.dirname, 'site')
const screens = [
  { name: 'phone', width: 360, height: 800, scale: 2 },
  { name: 'tablet', width: 768, height: 1024, scale: 1 },
  { name: 'laptop', width: 1280, height: 800, scale: 1 },
]
const kB = (names) => names.reduce((sum, n) => sum + statSync(join(site, 'img', n)).size, 0) / 1000
const list = (names) => (names.length ? `${names.join(', ')} (${kB(names).toFixed(1)} kB)` : 'nothing')

const browser = await chromium.launch()
console.log(file)
for (const s of screens) {
  const context = await browser.newContext({
    viewport: { width: s.width, height: s.height },
    deviceScaleFactor: s.scale,
  })
  const page = await context.newPage()
  // Answer requests for http://larkfield.test/ from the site folder.
  await page.route('http://larkfield.test/**', (route) =>
    route.fulfill({ path: join(site, new URL(route.request().url()).pathname) }))
  const requested = []
  page.on('request', (r) => {
    if (r.resourceType() === 'image') requested.push(basename(new URL(r.url()).pathname))
  })

  await page.goto(`http://larkfield.test/${file}`)
  await page.waitForTimeout(500)
  const onLoad = [...requested]
  const hero = await page.$eval('main img', (img) => ({
    src: img.currentSrc,
    shown: Math.round(img.getBoundingClientRect().width),
  }))
  const held = await page.$$eval('img[loading="lazy"]', (imgs) => imgs.map((img) => {
    const box = img.getBoundingClientRect()
    return `${Math.round(box.width)}x${Math.round(box.height)}`
  }))

  await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight))
  await page.waitForFunction(() => [...document.images].every((img) => img.complete && img.naturalWidth > 0))
  const later = requested.filter((n) => !onLoad.includes(n))

  const heroFile = basename(new URL(hero.src).pathname)
  const fileWidth = heroFile.match(/-(\d+)\.\w+$/)[1] // the file names carry their widths
  console.log(`${s.name} ${s.width}px at ${s.scale}x`)
  console.log(`  top photo: ${heroFile}, shown ${hero.shown}px wide, needs ${hero.shown * s.scale}px, file is ${fileWidth}px`)
  console.log(`  on load: ${list(onLoad)}`)
  console.log(`  after scrolling: ${list(later)}`)
  if (held.length) console.log(`  space held for lazy images before scrolling: ${held.join(', ')}`)
  await context.close()
}
await browser.close()
JS
node report.mjs srcset.html

Check it worked

The report prints three blocks. The phone's top photo line reads entrance-wide-960.jpg, shown 328px wide, needs 656px, file is 960px, and the laptop's reads shown 928px wide, needs 928px, file is 960px. The tablet also gets the 960 file. No screen downloads the 1600 file, and each downloads one image only. To see the same in your own browser, open site/srcset.html, open developer tools (F12), and run document.querySelector('img').currentSrc in the console: it names the file the browser chose. Narrow the window and reload with the cache disabled to watch it change.

Step 6 · Offer AVIF and WebP with picture

srcset chooses between widths of one format. To offer formats, wrap the image in <picture> and put a <source> in front of it for each format, with a type so the browser can skip the ones it cannot decode without downloading them. The browser uses the first <source> that it can use, and falls back to the <img>'s own srcset. Every source repeats sizes, because each one is a separate menu:

Bash
cd ~/responsive-images-demo
cat > site/formats.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Stage 2: formats</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<main>
  <h1>Visit Larkfield Clinic</h1>
  <picture>
    <source type="image/avif"
            srcset="img/entrance-wide-960.avif 960w, img/entrance-wide-1280.avif 1280w, img/entrance-wide-1600.avif 1600w"
            sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
    <source type="image/webp"
            srcset="img/entrance-wide-960.webp 960w, img/entrance-wide-1280.webp 1280w, img/entrance-wide-1600.webp 1600w"
            sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
    <img src="img/entrance-wide-960.jpg"
         srcset="img/entrance-wide-960.jpg 960w, img/entrance-wide-1280.jpg 1280w, img/entrance-wide-1600.jpg 1600w"
         sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)"
         width="1600" height="686"
         alt="The front entrance of Larkfield Clinic, with a ramp to the left of the door.">
  </picture>
</main>
</body>
</html>
HTML
node report.mjs formats.html

Order matters: AVIF first because it is usually smallest, then WebP, then the JPEG in the <img>. The <img> is required. It is the element that is drawn, so alt, width, height, loading and any class belong on it, never on <picture>. Current versions of Chrome, Edge, Firefox and Safari decode both AVIF and WebP, so the JPEG is for older browsers and some proxy browsers, which still turn up on older phones.

Check it worked

Every top photo line now names an .avif file at the same width as before: entrance-wide-960.avif on all three screens. Compare the on load sizes with the stage 1 report: the same pixels now cost noticeably fewer bytes, often something like a third to a half with these stand-ins, and the saving varies with the photo and the encoder build. In your browser's Network panel, filtered to images, the Type column shows avif for the photo on formats.html.

Step 7 · Give phones their own crop

The phone in the last report got a wide 21:9 strip, 328 by 141 pixels on screen. The door is in there, but small. Changing the crop, and not only the size, is called art direction, and it is the other job of <picture>: a <source> with a media condition is used only when the condition matches. Put the phone sources first, one per format, so a narrow screen matches them before it reaches the wide ones:

Bash
cd ~/responsive-images-demo
cat > site/crop.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Stage 3: a phone crop</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<main>
  <h1>Visit Larkfield Clinic</h1>
  <picture>
    <source media="(max-width: 37.5rem)" type="image/avif"
            srcset="img/entrance-phone-480.avif 480w, img/entrance-phone-720.avif 720w, img/entrance-phone-960.avif 960w"
            sizes="calc(100vw - 2rem)" width="960" height="540">
    <source media="(max-width: 37.5rem)" type="image/webp"
            srcset="img/entrance-phone-480.webp 480w, img/entrance-phone-720.webp 720w, img/entrance-phone-960.webp 960w"
            sizes="calc(100vw - 2rem)" width="960" height="540">
    <source media="(max-width: 37.5rem)"
            srcset="img/entrance-phone-480.jpg 480w, img/entrance-phone-720.jpg 720w, img/entrance-phone-960.jpg 960w"
            sizes="calc(100vw - 2rem)" width="960" height="540">
    <source type="image/avif"
            srcset="img/entrance-wide-960.avif 960w, img/entrance-wide-1280.avif 1280w, img/entrance-wide-1600.avif 1600w"
            sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
    <source type="image/webp"
            srcset="img/entrance-wide-960.webp 960w, img/entrance-wide-1280.webp 1280w, img/entrance-wide-1600.webp 1600w"
            sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
    <img src="img/entrance-wide-960.jpg"
         srcset="img/entrance-wide-960.jpg 960w, img/entrance-wide-1280.jpg 1280w, img/entrance-wide-1600.jpg 1600w"
         sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)"
         width="1600" height="686" fetchpriority="high"
         alt="The front entrance of Larkfield Clinic, with a ramp to the left of the door.">
  </picture>
  <p>Larkfield Clinic, 14 Mill Lane</p>
</main>
</body>
</html>
HTML
node report.mjs crop.html

Three details make this work:

  • The third phone source has no type. It holds the JPEG phone crop, so a phone browser without AVIF or WebP still gets the right shape and does not fall through to the wide JPEG in the <img>.
  • width and height on a <source> in a <picture> override the ones on the <img> when that source is used. The phone crop is 16:9, so its sources say 960 by 540, and the browser holds a 16:9 box on phones and a 21:9 box elsewhere.
  • The breakpoint, 37.5rem, is the same one the stylesheet uses. Keep crop switches on your layout's breakpoints, so the crop changes when the layout does.

This photo is the first thing on the page, so it also has fetchpriority="high" and no lazy loading. Improve Largest Contentful Paint explains why.

Check it worked

The phone's top photo line now reads entrance-phone-720.avif, shown 328px wide, needs 656px, file is 720px. The tablet and laptop still get entrance-wide-960.avif. Open site/crop.html and narrow the window below 600 pixels: the photo changes to the closer crop, and the image box changes from a long strip to a 16:9 shape.

Step 8 · Lazy-load the photos further down and hold their space

Now build the whole page. The reception and nurse photos sit in a gallery near the bottom, below plenty of text, so most visitors' first screen does not include them. Mark them loading="lazy": the browser then waits until they are near the visible area before fetching them, and a visitor who never scrolls that far never pays for them. Give each one width and height as well. With height: auto in the CSS, the browser uses the two numbers to work out the image's shape and holds a box of the right height before the file arrives, so the text below does not jump when it does.

Bash
cd ~/responsive-images-demo
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Visit Larkfield Clinic</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<main>
  <h1>Visit Larkfield Clinic</h1>

  <figure>
    <picture>
      <source media="(max-width: 37.5rem)" type="image/avif"
              srcset="img/entrance-phone-480.avif 480w, img/entrance-phone-720.avif 720w, img/entrance-phone-960.avif 960w"
              sizes="calc(100vw - 2rem)" width="960" height="540">
      <source media="(max-width: 37.5rem)" type="image/webp"
              srcset="img/entrance-phone-480.webp 480w, img/entrance-phone-720.webp 720w, img/entrance-phone-960.webp 960w"
              sizes="calc(100vw - 2rem)" width="960" height="540">
      <source media="(max-width: 37.5rem)"
              srcset="img/entrance-phone-480.jpg 480w, img/entrance-phone-720.jpg 720w, img/entrance-phone-960.jpg 960w"
              sizes="calc(100vw - 2rem)" width="960" height="540">
      <source type="image/avif"
              srcset="img/entrance-wide-960.avif 960w, img/entrance-wide-1280.avif 1280w, img/entrance-wide-1600.avif 1600w"
              sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
      <source type="image/webp"
              srcset="img/entrance-wide-960.webp 960w, img/entrance-wide-1280.webp 1280w, img/entrance-wide-1600.webp 1600w"
              sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)">
      <img src="img/entrance-wide-960.jpg"
           srcset="img/entrance-wide-960.jpg 960w, img/entrance-wide-1280.jpg 1280w, img/entrance-wide-1600.jpg 1600w"
           sizes="(min-width: 60rem) 58rem, calc(100vw - 2rem)"
           width="1600" height="686" fetchpriority="high"
           alt="The front entrance of Larkfield Clinic, with a ramp to the left of the door.">
    </picture>
    <figcaption>Larkfield Clinic, 14 Mill Lane</figcaption>
  </figure>

  <h2>Opening hours</h2>
  <p>Monday to Friday, 8:00 to 18:00. Saturday, 9:00 to 13:00. Closed on Sundays and public holidays.</p>

  <h2>Getting here</h2>
  <p>The clinic is on Mill Lane, two minutes' walk from the Larkfield Market bus stop. There is a ramp to the left of the main door and a lowered counter at reception.</p>

  <h2>What you can book</h2>
  <ul>
    <li>GP appointment</li>
    <li>Nurse appointment, for dressings, injections and checks</li>
    <li>Blood test</li>
    <li>Vaccination</li>
    <li>Medication review</li>
  </ul>

  <h2>Before your visit</h2>
  <p>Bring a list of any medicines you take, including ones you buy without a prescription. If you need an interpreter, tell us when you book and we will arrange one for your appointment.</p>
  <p>If you are running late, call reception. We will see you if we can, or move your appointment to the next free time.</p>

  <h2>Inside the clinic</h2>
  <div class="gallery">
    <figure>
      <picture>
        <source type="image/avif" srcset="img/reception-480.avif 480w, img/reception-720.avif 720w, img/reception-960.avif 960w"
                sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)">
        <source type="image/webp" srcset="img/reception-480.webp 480w, img/reception-720.webp 720w, img/reception-960.webp 960w"
                sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)">
        <img src="img/reception-480.jpg"
             srcset="img/reception-480.jpg 480w, img/reception-720.jpg 720w, img/reception-960.jpg 960w"
             sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)"
             width="960" height="640" loading="lazy"
             alt="A receptionist at the front desk of Larkfield Clinic, next to the check-in screen where you sign in on arrival.">
      </picture>
      <figcaption>Reception, where you check in</figcaption>
    </figure>
    <figure>
      <picture>
        <source type="image/avif" srcset="img/nurse-480.avif 480w, img/nurse-720.avif 720w, img/nurse-960.avif 960w"
                sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)">
        <source type="image/webp" srcset="img/nurse-480.webp 480w, img/nurse-720.webp 720w, img/nurse-960.webp 960w"
                sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)">
        <img src="img/nurse-480.jpg"
             srcset="img/nurse-480.jpg 480w, img/nurse-720.jpg 720w, img/nurse-960.jpg 960w"
             sizes="(min-width: 60rem) 28.5rem, (min-width: 37.5rem) calc(50vw - 1.5rem), calc(100vw - 2rem)"
             width="960" height="640" loading="lazy"
             alt="A Larkfield nurse checking a patient's blood pressure in a consulting room.">
      </picture>
      <figcaption>A consulting room</figcaption>
    </figure>
  </div>
</main>
</body>
</html>
HTML
node report.mjs

The gallery's sizes has three entries, one for each width rule in step 3, and the first matching condition wins, so the widest condition comes first. The loading attribute goes on the <img>, and it covers whichever source the browser picks. Never put it on the top photo: postponing the image a visitor sees first makes the page look slower.

Lazy does not mean "when it scrolls into view". Browsers start the fetch while the image is still some distance below the visible area, so it is ready by the time the visitor gets there, and that distance differs between browsers and connection speeds. Chromium's is generous: on a page as short as this one, it fetches the gallery straight away on every screen size. The attribute still matters, because real pages grow, and on a long article or a listing with dozens of photos it is the difference between downloading three images and thirty.

Check it worked

The report runs index.html by default. The phone's top photo is still entrance-phone-720.avif. On every screen, on load lists the entrance photo and both gallery photos, reception-720.avif and nurse-720.avif on the phone and the 480-pixel files on the tablet and laptop, and after scrolling says nothing: the gallery is within Chromium's look-ahead distance.

To see the deferral, make a copy of the page with a tall gap above the gallery, the way a long page would have, and report on it. This sed writes a new file and leaves index.html unchanged:

Bash
cd ~/responsive-images-demo
sed 's#<h2>Inside the clinic</h2>#<div style="height: 6000px"></div><h2>Inside the clinic</h2>#' site/index.html > site/long.html
node report.mjs long.html

Now on load lists only the entrance photo on all three screens, and after scrolling lists the two gallery files. The phone's last line reads space held for lazy images before scrolling: 328x219, 328x219, and the laptop's reads 456x304, 456x304: boxes of the right 3:2 shape, held by width and height before either file existed, so nothing below them moves when the photos arrive.

Then check the totals against the photo sheet's budgets of 80 KB per phone crop and 200 KB per desktop crop. With the stand-ins every file is far under. With real photos, re-run ./make-images.sh with lower quality settings, or choose a calmer photo, until each file fits. For a visitor on prepaid mobile data, which is how many of Larkfield's patients and many people across Africa get online, it adds up: compare the phone's total with ls -l site/img/entrance-wide-1600.jpg, the one file a page without any of this would send to every screen.

Step 9 · Clean up

Playwright keeps its browser outside the project folder. If you do not use Playwright for anything else, remove the browser this project downloaded, then delete the demo folder:

Bash
cd ~/responsive-images-demo
npx playwright uninstall
cd ~
rm -rf ~/responsive-images-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.