The <picture>
element in HTML provides a way to serve different images based on different conditions, such as the device’s screen size or pixel density. It allows you to define multiple <source>
elements within it, each specifying different image sources, and the browser will choose the most suitable image to display. Here’s how you can use the <picture>
element in HTML:
<picture>
<source srcset="path/to/image-large.jpg" media="(min-width: 1200px)">
<source srcset="path/to/image-medium.jpg" media="(min-width: 768px)">
<source srcset="path/to/image-small.jpg">
<img src="path/to/fallback-image.jpg" alt="Description of the image">
</picture>
Let’s break down the components of the <picture>
element:
<source>
Element:
Inside the<picture>
element, you can include one or more<source>
elements. Each<source>
element specifies a different image source using thesrcset
attribute and an optionalmedia
attribute to define the conditions for selecting that image source.
- The
srcset
attribute specifies the path or URL of the image and can include multiple sources separated by commas. Each source is followed by a descriptor that provides information about the image, such as its size or pixel density. - The
media
attribute specifies a media query that determines when the associated image source should be used. In the example above,media="(min-width: 1200px)"
specifies that the large image should be used when the viewport width is at least 1200 pixels,media="(min-width: 768px)"
specifies that the medium image should be used when the viewport width is at least 768 pixels, and the last<source>
element without amedia
attribute provides a fallback option for smaller screens.
<img>
Element:
The<img>
element is placed as the last child of the<picture>
element and serves as the fallback option. If none of the<source>
elements match the conditions or if the browser doesn’t support the<picture>
element, the<img>
element’s source specified by thesrc
attribute will be used.
- The
src
attribute of the<img>
element specifies the path or URL of the fallback image.
The browser will evaluate the <source>
elements in the order they appear and select the first matching source based on the media
attribute and other conditions. If no matching source is found, the fallback image specified by the <img>
element will be used.
Using the <picture>
element with <source>
elements allows you to serve different images based on specific conditions, optimizing the images for different devices and screen sizes. This can help improve the performance and user experience of your website.