<Picture> element is a container that allows developers to specify multiple image resources for different display conditions. It works by containing one or more <source> elements and a single fallback <img>element, enabling the browser to choose the most appropriate image automatically.
Key Differences from <img>
While the standard <img> tag is suitable for a single source, the <picture> tag provides flexibility for responsive design and art direction.
Syntax and Attributes
The <picture>element itself does not have specific attributes; functionality is derived from its child elements:
<source>: Defines alternative image sources. Common attributes include:
media: Specifies a media query (e.g., (min-width: 800px)) to determine when this source is used.
srcset: Provides the URL and optional width/pixel density descriptors for the image.
type: Specifies the MIME type (e.g., image/webp) to enable format switching.
<img>: Acts as the fallback option. It must be the last child element and includes the src and alt attributes to ensure compatibility with browsers that do not support the tag.
<picture>
<source media="(min-width: 1200px)" srcset="large.jpg" type="image/jpeg">
<source media="(min-width: 800px)" srcset="medium.jpg" type="image/jpeg">
<img src="default.jpg" alt="Example image">
</picture>
Top comments (0)