CodeBlanks Logo Icon CodeBlanks

Media attribute

HTML course · Advanced · Lesson 8/56

Switch images per screen with <source media="...">.

What is the media attribute?

Adding a media attribute to a <source> tells the browser which screen condition should pick that source. The value uses the same syntax as a CSS @media rule.

For example, media="(max-width: 600px)" fires only on narrow screens, media="(orientation: portrait)" only when held upright. The browser picks the first source whose condition matches and skips the rest. So order matters: put specific conditions first, general ones last.

What is art direction?

Art direction means showing different crops of the same scene on different screens. A wide landscape works on desktop; on a phone the people in it become too small. So you serve a tighter crop that pulls faces closer.

With srcset only the resolution changes, the crop stays the same. With <picture> and media the crop itself changes. So srcset swaps the size of the same image; media with <picture> swaps the image itself.

Exercise Write two sources, media and an img

Add a <picture> to body. Put two <source> tags inside: the first with media set to (min-width: 800px) and srcset set to news-wide.jpg; the second with media set to (max-width: 799px) and srcset set to news-narrow.jpg. Finish with an <img> whose src is news-narrow.jpg and alt is News image.

Show example solution
<body>
  <picture>
    <source media="(min-width: 800px)" srcset="news-wide.jpg">
    <source media="(max-width: 799px)" srcset="news-narrow.jpg">
    <img src="news-narrow.jpg" alt="News image">
  </picture>
</body>

Test yourself

  1. When is <source media="(min-width: 800px)"> picked?

    • When the viewport is at least 800 px wide
    • When the viewport is at most 800 px wide
    • When the image weighs at least 800 bytes
    • When the browser has loaded for 800 ms
    Show answer

    When the viewport is at least 800 px wide — Correct. min-width: 800px means the viewport is at least 800 px wide.

  2. Write the media attribute on source

    <picture>
      <source ____="(min-width: 768px)" srcset="hero-wide.jpg">
      <img src="hero-narrow.jpg" alt="Hero image">
    </picture>
    Show answer
    <picture>
      <source media="(min-width: 768px)" srcset="hero-wide.jpg">
      <img src="hero-narrow.jpg" alt="Hero image">
    </picture>
  3. Match each media query to its meaning

    (min-width: 800px)
    At least 800 px wide
    (max-width: 600px)
    At most 600 px wide
    (orientation: portrait)
    Held upright
    (orientation: landscape)
    Held sideways

All lessons in Advanced