Course contentsShow
← Web Development
Lesson 424 of 2,9827. Responsive DesignFree lesson

Modern Image Formats with Picture

Serving WebP or AVIF with JPEG/PNG fallbacks using type attributes in picture sources.

Modern Image Formats with Picture

What you'll learn: How to serve next-generation image formats like WebP or AVIF while providing automatic fallbacks for older browsers.

The Problem with New Formats

Modern formats like WebP and AVIF create dramatically smaller files than JPEG or PNG—sometimes 30-50% smaller—which means faster page loads. But not every browser supports them yet. You need a way to serve the best format each browser can handle.

The type Attribute Solution

Inside a <picture> element, each <source> can specify a type attribute. This tells the browser what image format is being offered. The browser automatically picks the first source it understands and ignores the rest:

<picture>
  <source srcset="photo.avif" type="image/avif">
  <source srcset="photo.webp" type="image/webp">
  <img src="photo.jpg" alt="A sunset">
</picture>

The browser reads from top to bottom:

  1. Can it display AVIF? Yes → use photo.avif and stop.
  2. Can it display WebP? Yes → use photo.webp and stop.
  3. Otherwise: Fall back to the <img> tag's photo.jpg.

Think of it like a restaurant menu where you order the first dish that's available—if they're out of today's special, you try the next option, then the classic standby.

Why This Matters

You get performance (smaller files for modern browsers) and compatibility (older browsers still see images) without JavaScript, extra logic, or server detection. The browser does all the work.

Key Takeaway: Use the type attribute in <picture> sources to serve modern formats like WebP/AVIF with automatic JPEG/PNG fallbacks—browsers will pick the best format they support.