<picture>
The <picture>
tag allows you to adjust the content of an image based on the user's display conditions, such as:
- screen size;
- or resolution.
It is used to provide specific images for different contexts, ensuring better performance and adaptability.
It is generally combined with the
<source>
and<img>
tags to offer maximum flexibility. 😉
Structure and syntax of the <picture>
tag
Basic structure and syntax
The <picture>
tag contains <source>
elements that define different images to load based on specific conditions (such as screen width or resolution).
Then, the <img>
element provides a fallback image if none of the <source>
conditions are met.
Let's take a small generic example:
<picture>
<source srcset=[path to image for small screen] media="(max-width: 600px)">
<source srcset=[path to image for large screen] media="(min-width: 601px)">
<img src=[path to default image] alt="image description">
</picture>
Here are some explanations:
<source>
: This tag is used within<picture>
to specify different images and their display conditions. Thesrcset
attribute contains the URL of the image, and themedia
attribute allows you to define CSS conditions (such as screen width or resolution, as with responsive design);<img>
: The<img>
element is used as a fallback in case none of the<source>
conditions are met. It contains thesrc
attribute with the URL of the default image and thealt
attribute to provide a description of the image.
Usage example
Let's take the example of a responsive image with different screen sizes:
<picture>
<source srcset="images/small.jpg" media="(max-width: 600px)">
<source srcset="images/medium.jpg" media="(min-width: 601px) and (max-width: 1200px)">
<source srcset="images/large.jpg" media="(min-width: 1201px)">
<img src="images/default.jpg" alt="Responsive image with different sizes">
</picture>
In this example:
- An image
small.jpg
is used for screens smaller than 600px; - An image
medium.jpg
is used for screens between 601px and 1200px; - An image
large.jpg
is used for screens larger than 1200px; - If none of the criteria are met, the default image
default.jpg
is displayed.
Attributes
All "classic" attributes can be used with the <picture>
tag (such as title
for example, to define a title that will be displayed on hover in a tooltip).
Browser compatibility
Browser | Compatibility with <picture> |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | No |