Providing Fallbacks with Picture Element
What you'll learn: How to serve modern image formats like AVIF and WebP while automatically falling back to JPEG or PNG for browsers that don't support them.
Modern image formats like AVIF and WebP offer significantly smaller file sizes than traditional JPEG or PNG, but not all browsers support them yet. The <picture> element lets you serve these cutting-edge formats to browsers that understand them, while automatically providing a safe fallback for older browsers—all without JavaScript.
How Format Fallbacks Work
Think of the <picture> element like a restaurant menu with daily specials. The browser reads from top to bottom, checking each <source> option. When it finds a format it can handle (using the type attribute), it serves that image and stops looking. If it doesn't recognize any of the modern formats, it falls back to the traditional <img> element at the bottom.
The Pattern
<picture>
<source srcset="photo.avif" type="image/avif">
<source srcset="photo.webp" type="image/webp">
<img src="photo.jpg" alt="A scenic mountain view">
</picture>
The browser checks AVIF first (smallest file), then WebP (also efficient), and finally uses the JPEG if neither is supported. The <img> element is mandatory—it's both the fallback and what screen readers use for accessibility.
Order Matters
Always list formats from most modern to least modern. The browser picks the first format it recognizes, so putting JPEG first would defeat the purpose—modern browsers would never get the optimized files.
Key Takeaway: The <picture> element with type attributes lets you serve modern, smaller image formats while guaranteeing compatibility with older browsers through automatic fallback to JPEG or PNG.