Emmanuel Akinfulubi

HTML and CSSHTML and CSS

Responsive images with the picture element in HTML

6 Offer a different image at a different width

fair

Use <picture> to swap in a wider crop on a large screen, while keeping one image that always works.

Stuck? Three hints, smallest first
  1. 1. <source media="..."> lines up before the <img>; the first match wins.
  2. 2. The <img> is not optional. It is the fallback and the thing that carries alt.
  3. 3. Sources are checked in order, so put the narrowest condition where you mean it.

index.html

<picture>
  <!-- Only on a wide viewport. The preview frame is narrower than this, so the
       fallback below is what you see rendered. -->
  <source media="(min-width: 60em)" srcset="park-wide.svg">
  <img
    class="hero"
    width="240" height="120"
    alt="The terminal frontage, seen from the road"
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='120'%3E%3Crect width='240' height='120' fill='%230b3a8f'/%3E%3Crect x='24' y='72' width='192' height='24' fill='%23ffd75e'/%3E%3C/svg%3E">
</picture>

style.css

picture {
  display: block;
  max-width: 240px;
}

.hero {
  display: block;
  width: 100%;
  height: auto;
  border-radius: 8px;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
8 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 6

test('a picture element is used', hasTag(html, 'picture'), true);
test('with one conditional source', countTag(html, 'source'), 1);
test('the condition is a media query', /media="\(min-width: 60em\)"/.test(html), true);
test('there is exactly one img, which is the fallback', countTag(html, 'img'), 1);
test('the alt lives on the img, not on the source', /<img[\s\S]*alt="/.test(html) && /<source[^>]*alt=/.test(html) === false, true);
test('the source comes before the img, because order decides', html.indexOf('<source') < html.indexOf('<img'), true);
test('the img still reserves its box', /width="240"/.test(html) && /height="120"/.test(html), true);
test('and its own src is inline, so the fallback needs no network', /src="data:image/.test(html), true);

Output


      

<picture> is a wrapper around one <img>, not a replacement for it: the <img> is what renders, what carries alt, and what a browser with no <picture> support falls back to. Sources are evaluated top to bottom and the first matching one wins, so a broad condition placed first shadows everything after it. The wide-screen source here names a file this course does not ship, which is why the note above the markup says the preview always shows the fallback.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.