Challenge - Responsive image
Write a hero with <picture> that changes per screen and format.
Responsive image challenge
This challenge tests the full responsive image topic: the <picture> wrapper, <source> for screen and format selection, the <img> fallback, and performance settings.
You will build a hero image: media for narrow and wide crops, type="image/webp" for a modern format, srcset and sizes for resolution choice, loading="lazy" and decoding="async" for smooth loading, and width with height to reserve space. Wrap it in <figure> with a <figcaption>.
Exercise Write the hero image from scratch
Add a <figure> to body. Put a <picture> inside. Inside picture write two <source> tags: the first with media="(min-width: 800px)" and srcset="/img/hero-wide.jpg", the second with type="image/webp" and srcset="/img/hero.webp". As the last child of picture add an <img> with src="/img/hero-narrow.jpg", alt="Mountain landscape", width="1200", height="600", loading="lazy", decoding="async", srcset="/img/hero-narrow.jpg 600w" and sizes="100vw". After picture add a <figcaption> with a caption.
Show example solution
<body>
<figure>
<picture>
<source media="(min-width: 800px)" srcset="/img/hero-wide.jpg">
<source type="image/webp" srcset="/img/hero.webp">
<img src="/img/hero-narrow.jpg"
alt="Mountain landscape"
width="1200" height="600"
loading="lazy" decoding="async"
srcset="/img/hero-narrow.jpg 600w"
sizes="100vw">
</picture>
<figcaption>The view above is striking.</figcaption>
</figure>
</body>
Test yourself
-
Which attribute selects a source by screen width?
- srcset
- sizes
- media
- type
Show answer
media — Correct. The media attribute defines a screen condition; when it matches, that source is chosen.
-
Write the WebP source
<picture> <source ____="image/webp" srcset="/img/hero.webp"> <img src="/img/hero-narrow.jpg" alt="Mountain landscape"> </picture>Show answer
<picture> <source type="image/webp" srcset="/img/hero.webp"> <img src="/img/hero-narrow.jpg" alt="Mountain landscape"> </picture> -
Match each attribute to its role
- media
- Screen condition
- type
- File format
- srcset
- Image path
- sizes
- Viewport width
- loading
- Load timing