HTML <picture> Element

Publish in HTML Tutorial el 25/05/2025 14:53

The HTML <picture> element serves as a container for zero or more <source> elements and one <img> element. Its primary purpose is to provide alternative image resources for different display/device scenarios, enabling responsive images without using CSS or JavaScript.


Key features:

  • Art direction - show different cropped images for different viewports
  • Image format selection - serve modern formats to supporting browsers
  • Resolution switching - serve smaller images to smaller devices
  • Fallback to standard <img> if no sources match


Basic Syntax

Here's the basic structure of the <picture> element:


Examples

1. Basic Responsive Image

This example shows different images based on viewport width:

Play Code


2. Modern Image Formats

Serve WebP to supporting browsers, fallback to JPEG:

Play Code


3. Density Switching

Serve higher resolution images to high-DPI devices:

Play Code


4. JavaScript Interaction (Change Image on Click)

This example shows how to change the picture source using JavaScript:

Play Code


5. JavaScript Art Direction (Change Based on Screen Size)

Dynamically update image sources when window is resized:

Play Code


Tips and Tricks

  • Always include the <img> tag as the last child - it serves as the fallback
  • Order matters - browsers use the first matching <source>
  • Combine media and type - you can use both attributes on a single <source>
  • Use descriptive alt text - important for accessibility and SEO
  • Consider using sizes attribute with srcset for better control


Browser Support

The <picture> element is supported in all modern browsers (Chrome, Firefox, Safari, Edge) since 2015. For older browsers, the <img> fallback ensures your content remains accessible.

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...