The <picture> Element Structure
What you'll learn: How the <picture> element is organized with <source> children and a fallback <img> element.
When you need to serve completely different images based on screen conditions (art direction), the <picture> element acts as a container that wraps multiple image sources. Think of it like a restaurant menu where the kitchen picks the best dish based on your dietary restrictions—the browser chooses which image to display.
Basic Anatomy
The <picture> element itself doesn't display anything. Instead, it contains:
- One or more
<source>elements – Each defines an image option with conditions - Exactly one
<img>element – The actual image tag that displays content and acts as the fallback
<picture>
<source media="(min-width: 800px)" srcset="wide-image.jpg">
<source media="(min-width: 400px)" srcset="medium-image.jpg">
<img src="small-image.jpg" alt="A scenic landscape">
</picture>
How It Works
The browser reads the <source> elements from top to bottom, checking each media condition. When it finds the first match, it uses that source's srcset. If no <source> matches (or the browser doesn't support <picture>), it falls back to the <img> element.
Critical: The <img> tag is not optional—it's where the alt text lives and what older browsers display. Only the <img> actually renders; <picture> and <source> are just instructions.
Why This Structure?
This separation lets you completely swap images (like a horizontal crop for wide screens, vertical crop for narrow screens) while keeping semantic fallback support. The <source> elements enhance the basic <img>, which remains fully functional on its own.
Key Takeaway: The <picture> element contains <source> elements with conditions and always includes one <img> element that provides the fallback and accessibility text.