Responsive Images with Multiple Formats
Implement responsive images using the HTML picture element with AVIF, WebP, and JPEG fallbacks. Learn srcset, sizes, and format negotiation strategies.
Web Development
Detailed Explanation
Serving Multiple Image Formats for Responsive Design
Modern web development requires serving the right image format to each browser while handling different screen sizes. The HTML <picture> element makes this possible.
The Picture Element Pattern
<picture>
<!-- Best compression, newest format -->
<source
srcset="photo-400.avif 400w,
photo-800.avif 800w,
photo-1200.avif 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
type="image/avif">
<!-- Good compression, wide support -->
<source
srcset="photo-400.webp 400w,
photo-800.webp 800w,
photo-1200.webp 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
type="image/webp">
<!-- Universal fallback -->
<img
srcset="photo-400.jpg 400w,
photo-800.jpg 800w,
photo-1200.jpg 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
src="photo-800.jpg"
alt="Description of the photo"
loading="lazy"
decoding="async">
</picture>
How Browser Format Negotiation Works
- Browser reads
<source>elements top to bottom - Checks if it supports the
type(MIME type) - If supported, uses that source's
srcsetandsizes - If not, moves to the next
<source> - Falls back to the
<img>element if no source matches
Generating All Format Variants
For each source image, you need to generate:
- 3 sizes (small, medium, large) x 3 formats (AVIF, WebP, JPEG) = 9 files
Use this converter to create each variant:
- Upload the original high-resolution image
- Convert to AVIF, WebP, and JPEG at appropriate quality
- Resize each to the needed dimensions (use an image resizer tool)
Quality Settings per Format
| Format | Recommended Quality | Notes |
|---|---|---|
| AVIF | 65-75% | Best compression, lower number OK |
| WebP | 75-85% | Good balance |
| JPEG | 80-85% | Universal fallback |
CDN-Based Format Negotiation
Many CDNs (Cloudflare, Cloudinary, imgix) can automatically serve the best format based on the browser's Accept header, eliminating the need for multiple <source> elements.
Use Case
Frontend developers implementing responsive image strategies. Preparing multiple format variants of each image is a key step in modern web performance optimization.