HTML <picture> Tag
The <picture> element is a container for one or more <source> elements and one <img> element, which is the last child element in the block.
The <source> element contains versions of an image for different display device scenarios. The <img> element describes the image’s size and other attributes. The browser considers each of the child <source> elements and loads the most appropriate image. If no matches are found, the browser displays the image specified by the <img> tag.
The <picture> element allows specifying multiple images to better adapt to different viewport sizes, avoiding the need to scale a single image. It can be used for the following purposes:
- to crop and modify images for different media conditions,
- to offer alternative image formats when specific formats are not supported.
Note: The object-position and object-fit properties apply to the <img> fallback element to control its sizing and alignment within the container.
The <picture> tag is new in HTML5.
Syntax
The <picture> tag comes in pairs. The content is written between the opening (<picture>) and closing (</picture>) tags.
HTML <picture> Tag
<picture>
<source media="...">
<source media="...">
<img src="...">
</picture>Example of the HTML <picture> tag:
HTML <picture> Tag
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<picture>
<source media="(min-width: 650px)" srcset="https://www.w3docs.com/uploads/media/news_gallery/0001/01/thumb_348_news_gallery_list.jpeg" />
<source media="(min-width: 430px)" srcset="https://www.w3docs.com/uploads/media/news_gallery/0001/01/thumb_316_news_gallery_list.jpeg" />
<img src="https://www.w3docs.com/uploads/media/news_gallery/0001/01/thumb_366_news_gallery_list.jpeg" alt="img" style="width:auto;" />
</picture>
<p>Some information about pictures</p>
</body>
</html>The browser evaluates <source> elements in order and loads the first one whose media query matches the current viewport. If no <source> matches, it falls back to the <img> element. The <picture> element is widely supported in all modern browsers.
Attributes
These attributes apply to the <source> elements inside <picture>:
| Attribute | Value | Description |
|---|---|---|
| media | media_query | Specifies a media query to match the viewport size. |
| srcset | URL | Specifies the URL of the image to use in different situations. |
| sizes | length | Specifies the width of the image for different viewport sizes. |
| type | MIME_type | Specifies the MIME type of the linked resource (e.g., image/webp). |
| src | URL | Specifies the URL of the image. Used as an alternative to srcset. |
Each <source> element must include either a srcset or src attribute. The fallback <img> element uses the src attribute.
The <picture> tag supports the Global Attributes.
Practice
What is a function of the HTML <picture> tag?