The <picture>
element in HTML enhances the ability of web developers to define various image sources for different scenarios.
Within the <picture>
element, there are multiple <source>
elements, each pointing to distinct images via the srcset
attribute. This enables the browser to select the most appropriate image based on the current viewing conditions or device specifications.
The media
attribute associated with each <source>
element specifies the conditions under which a particular image is deemed most fitting, allowing for more responsive and adaptive image display across various devices and screen sizes.
<picture> <source media=”(min-width: 650px)” srcset=”image1.jpg”> <source media=”(min-width: 465px)” srcset=”image2.jpg”> <img src=”img_flower.jpg”> </picture> |
Note: Always place an <img> element as the last child within the <picture> element. Browsers that lack support for the <picture> element, or instances where none of the <source> tags match, will resort to using the <img> element. |
The <picture> element serves two primary purposes:
If your screen or device is compact, loading a large image file isn’t essential. The browser will prioritize the first <source> element that aligns with attribute values and disregard subsequent elements.
<picture> <source srcset=”image1.png”> <source srcset=”img_flower.jpg”> <img src=”img_farms.gif” alt=”Farms” style=”width:auto;”> </picture> |
Note: The browser will select the initial <source> element that matches the attribute values and disregard any subsequent <source> elements. |