Media Queries in Picture Sources
You'll learn how to use the media attribute inside <source> elements to load different images based on viewport size, enabling true art direction.
What Are Media Queries in Picture Sources?
When you use the <picture> element for art direction (showing a different crop or composition at different screen sizes), you need a way to tell the browser when to use each image. This is where the media attribute comes in.
The media attribute works just like CSS media queries. You write a condition (like min-width: 768px), and the browser will only use that <source> if the condition matches. The browser evaluates sources in order and uses the first one that matches.
How It Works
<picture>
<source
media="(min-width: 1024px)"
srcset="wide-landscape.jpg">
<source
media="(min-width: 768px)"
srcset="medium-crop.jpg">
<img src="mobile-portrait.jpg" alt="Product photo">
</picture>
At desktop widths (≥1024px), the wide landscape version loads. On tablets (≥768px but <1024px), a medium crop loads. On phones, the fallback <img> loads the portrait version.
Think of it like a decision tree: The browser walks down the list asking "Does this media query match right now?" The first "yes" wins.
Order Matters
Always arrange sources from most specific to least specific (typically largest to smallest). The <img> tag acts as the ultimate fallback when no <source> matches.
Unlike srcset (which provides hints), media gives the browser explicit instructions: "Use this image if this condition is true."
Key Takeaway: The media attribute in <source> elements lets you specify exactly which image to load at different viewport sizes, giving you complete control over art direction in responsive images.