Web Foundations

Picture Element

Responsive images, art direction, format selection, and performance.

Advertisement

Picture Element

Responsive images, art direction, format selection, and performance.

Overview

The <picture> element provides art direction and format fallbacks.

Key Concepts

  • Source Elements — Multiple image sources
  • Media Queries — Responsive image selection
  • Type Attribute — Format fallbacks
  • Art Direction — Different crops per viewport
  • Performance — Optimize image loading

Code Examples

<!-- Format fallbacks -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Description" width="800" height="600">
</picture>

<!-- Responsive with art direction -->
<picture>
  <source media="(min-width: 1200px)" srcset="hero-large.jpg">
  <source media="(min-width: 768px)" srcset="hero-medium.jpg">
  <img src="hero-small.jpg" alt="Hero image" class="hero-img">
</picture>

<!-- Multiple densities -->
<picture>
  <source srcset="image@2x.avif 2x, image.avif 1x" type="image/avif">
  <source srcset="image@2x.webp 2x, image.webp 1x" type="image/webp">
  <img src="image.jpg" alt="Description" width="400" height="300">
</picture>

<!-- Complete responsive image -->
<picture>
  <!-- Desktop - wide crop -->
  <source 
    media="(min-width: 1200px)" 
    srcset="product-wide.avif 1x, product-wide@2x.avif 2x"
    type="image/avif"
  >
  <source 
    media="(min-width: 1200px)" 
    srcset="product-wide.webp 1x, product-wide@2x.webp 2x"
    type="image/webp"
  >
  <source 
    media="(min-width: 1200px)" 
    srcset="product-wide.jpg 1x, product-wide@2x.jpg 2x"
  >
  
  <!-- Mobile - square crop -->
  <source 
    media="(max-width: 767px)" 
    srcset="product-square.avif 1x, product-square@2x.avif 2x"
    type="image/avif"
  >
  <source 
    media="(max-width: 767px)" 
    srcset="product-square.webp 1x, product-square@2x.webp 2x"
    type="image/webp"
  >
  
  <!-- Fallback -->
  <img 
    src="product.jpg" 
    alt="Product name" 
    width="800" 
    height="600"
    loading="lazy"
    decoding="async"
  >
</picture>

<style>
.hero-img {
  width: 100%;
  height: auto;
  object-fit: cover;
}
</style>

Practice

Implement responsive images with art direction for a hero section.

Advertisement