Using <source> with media Attributes
What you'll learn: How to control which image displays at different screen sizes using media queries inside <source> elements.
You've already learned about the <picture> element structure. Now it's time to make those <source> elements smart by adding media attributes that tell the browser when to use each image source.
How It Works
Think of <source> elements with media attributes like a set of rules the browser checks from top to bottom:
- "If the screen is at least 1200px wide, use this image"
- "If the screen is at least 768px wide, use this image"
- "Otherwise, use the default image in the
<img>tag"
The browser evaluates each media attribute as a media query (just like in CSS) and picks the first one that matches.
The Pattern
<picture>
<source media="(min-width: 1200px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive image">
</picture>
In this example:
- On wide desktop screens (1200px+),
large.jpgdisplays - On tablets (768px-1199px),
medium.jpgdisplays - On phones (below 768px),
small.jpgdisplays
Order Matters
Always place your <source> elements from most specific to least specific (typically largest to smallest viewport). The browser stops at the first match, so if you put the smallest media query first, larger ones might never trigger.
You can use any valid CSS media query: (orientation: landscape), (max-width: 600px), or even (min-width: 768px) and (orientation: portrait).
Key Takeaway: The media attribute in <source> elements lets you serve different images based on viewport width or other conditions, giving you precise control over art direction across devices.