CodeBlanks Logo Icon CodeBlanks

Picture and source

HTML course · Advanced · Lesson 7/56

Learn image selection with <picture> and <source>.

What is picture for?

In earlier lessons you used <img> with srcset to serve one image at several resolutions. But what if you want a different crop on mobile than on desktop? That is what <picture> is for.

<picture> is a wrapper: you place <source> tags inside and finish with an <img>. The browser tries each source in order and picks the matching one; if none fits, it falls back to the <img>. This lets you do art direction.

The source tag and the img fallback

A <source> shows nothing on its own; it lives inside a <picture>. It usually takes two attributes: srcset for the image path and media for the screen condition.

Key point: the last child of <picture> must always be an <img>. This <img> is shown when no source fits, and the browser reads its alt text and sizes from it. So accessibility and fallback both come from the <img>.

Selecting a source with media

When you write several <source> tags, the browser tries them top to bottom. Give each a media attribute and the first one whose condition matches wins.

For instance, <source media="(min-width: 800px)" srcset="wide.jpg"> is used when the viewport is at least 800 px wide; otherwise the browser moves on. This is ideal for a square crop on mobile and a wide landscape on desktop.

Exercise Write picture, source and img

Add a <picture> to body. Inside it put a <source> whose srcset attribute is landscape-wide.jpg. Then add an <img> with src set to landscape-narrow.jpg and alt set to Mountain view.

Show example solution
<body>
  <picture>
    <source srcset="landscape-wide.jpg">
    <img src="landscape-narrow.jpg" alt="Mountain view">
  </picture>
</body>

Test yourself

  1. What is the core purpose of <picture>?

    • Add a background image to the page
    • Compress the image and shrink its size
    • Pick the right image from different sources
    • Auto-fix the colours of the image
    Show answer

    Pick the right image from different sources — Correct. picture picks the right image from different sources.

  2. Write source inside picture

    <picture>
      <____ srcset="landscape-wide.jpg">
      <img src="landscape-narrow.jpg" alt="Mountain view">
    </picture>
    Show answer
    <picture>
      <source srcset="landscape-wide.jpg">
      <img src="landscape-narrow.jpg" alt="Mountain view">
    </picture>
  3. Match each tag to its role

    <picture>
    Image selection wrapper
    <source>
    Source and condition
    <img>
    Final fallback image
    srcset
    Image path

All lessons in Advanced