<picture> HTML element is used to provide multiple sources or versions of an image, allowing the browser to choose the most suitable one based on the user’s device, screen resolution, or other factors. It is commonly used for responsive images to ensure optimal display across different devices and screen sizes.
Here’s an example of how to use the
<picture> <source srcset="image-large.jpg" media="(min-width: 768px)" /> <source srcset="image-medium.jpg" media="(min-width: 480px)" /> <img src="image-small.jpg" alt="Image description" /> </picture>
In this example, the
<picture> element contains multiple
<source> elements and an
<img> element. Each
<source> element provides a different version of the image with its respective
srcset attribute and a
media attribute that defines the conditions under which it should be used. The
srcset attribute specifies the image source URL or path, and the
media attribute specifies the media query that the browser should evaluate to determine if the source should be used. The
<img> element is used as a fallback, providing an image that will be displayed if none of the
<source> elements are matched.
The browser evaluates the
<source> elements from top to bottom and selects the first one with a matching
media query. This allows you to provide different image versions for different screen sizes or device capabilities, improving performance and user experience.
It’s important to provide appropriate image formats and resolutions for each source, considering factors like image quality, file size, and device compatibility. The
srcset attribute can include multiple image sources separated by commas, each with an optional descriptor indicating the image size or pixel density. This allows the browser to choose the most suitable image based on the device’s capabilities.
In summary, the
<picture> element is used to provide multiple sources or versions of an image, enabling the browser to choose the most appropriate one based on factors like device capabilities and screen size. By using the
<picture> element with
<img> elements, you can create responsive and optimized images for different devices, improving performance and user experience.