HTML <picture>
Tag
The HTML <picture>
tag is used to specify multiple sources for an image element. It allows the browser to choose the most appropriate image source depending on factors like screen resolution or viewport size.
How to Use the <picture>
Tag
To use the <picture>
tag, you need to specify one or more <source>
elements inside the <picture>
tag. Each <source>
element should include the srcset
attribute with the URL of the image source and the media
attribute to define the conditions under which that source should be used. Finally, add an <img>
element as the last child of the <picture>
tag to provide a default image source in case none of the conditions match.
Main Attributes of the <picture>
Tag
Attribute | Description |
---|---|
srcset |
Specifies the URL of the image source to be used. |
media |
Specifies the conditions under which the image source should be used. |
Example of Using the <picture>
Tag
<picture>
<source srcset="image-large.jpg" media="(min-width: 1024px)">
<source srcset="image-medium.jpg" media="(min-width: 768px)">
<img src="image-small.jpg" alt="Fictional Image">
</picture>
In this example, the browser will choose the appropriate image source based on the screen width. If the viewport width is at least 1024px, it will use "image-large.jpg". If the viewport width is at least 768px but less than 1024px, it will use "image-medium.jpg". If the viewport width is less than 768px, it will use "image-small.jpg".