Responsive <picture>
Overview
The standard <img> tag forces the browser to download a single image file, regardless of the user's device. If you serve a massive 4K desktop banner image to a user on a tiny 4G mobile phone, it wastes their data and ruins performance. The <picture> element solves this. It acts as a wrapper that provides multiple different image files and relies on CSS-style media queries to let the browser intelligently choose the exact right image for the current screen size or supported file format.
Syntax
<picture>
<!-- If the browser supports modern, highly-compressed WebP or AVIF formats -->
<source type="image/avif" srcset="banner.avif">
<source type="image/webp" srcset="banner.webp">
<!-- Art Direction: Serve a square image on mobile, wide image on desktop -->
<source media="(max-width: 768px)" srcset="banner-mobile-square.jpg">
<source media="(min-width: 769px)" srcset="banner-desktop-wide.jpg">
<!-- The absolute FALLBACK if none of the above match or work -->
<!-- This standard img tag is what actually gets rendered to the screen -->
<img src="banner-fallback.jpg" alt="Promotional Banner" width="1200" height="600">
</picture>Common Pitfalls
- Forgetting the fallback
<img>tag. The<picture>and<source>tags do absolutely nothing visual on their own. They simply feed data to the fallback<img>tag nestled inside. If you forget the<img>, nothing will render. - Putting styling (
class,width,height) on the<picture>tag itself. You must apply all CSS classes and dimensions directly to the inner fallback<img>tag.
Interview Questions
Art Direction is serving completely differently cropped images based on screen size (e.g., zooming in on a subject's face for mobile, but showing a wide landscape for desktop) to maintain visual impact, which is easily achieved using <source media="...">.
Real-World Example
Serving next-generation image formats while remaining compatible with legacy browsers like Internet Explorer.
<picture>
<!-- Modern browsers will grab the WebP (much smaller file size) -->
<source type="image/webp" srcset="/images/logo.webp">
<!-- Legacy browsers ignore the <source> tag entirely and just render the PNG -->
<img src="/images/logo.png" alt="Company Logo" width="200" height="50">
</picture>Check Your Knowledge
Test your understanding of Responsive <picture> with these quick questions.