picture element | picture object

The picture element is a container that contains multiple source elements to its contained img element. The browser will select which source to use based on numerous factors such as screen pixel density, viewport size, and file type.

DOM Information

Inheritance Hierarchy

 Node
  Element
   HTMLElement
     picture

Standards information

Remarks

There can be zero or more source elements nested within a picture element.

An img element must be nested as the last child.

The source element's src attribute has no meaning when it is nested within the picture element. In order to set the image source of a source element, the srcset attribute must be utilized.

The picture element does not display anything. Instead, it provides a context for its contained img element so that it may choose from multiple URLs.

The type and media attributes are used by the browser to pick the first source element where both of the attributes evaluate to true. The type attribute allows you to denote the MIME type of the image you will be providing. This allows you to provide specific image formats only to browsers that support them. The media attribute allows you to provide a media query list, which when valid cues the browser to analyze the srcset of that source. The following code snippet shows an example of type being used to show that an image is a .png file.


<picture>
   <source srcset="sample_image.png" type="image/png">
   <img src="fallback.jpeg">
</picture>


Both the media and type attributes are optional. The only required attribute for a source element is the srcset attribute.

Examples

This example uses the picture element to display different images, and different resolutions of those images depending on the width of the viewport. To ensure that all browsers will be able to display an image, an img tag should be included to support browsers that don't support the picture element.


<picture>
   <source media="(min-width: 600px)" srcset="large.png, large-double.png 2x">
   <source media="(min-width: 400px)" srcset="medium.png, medium-double.png 2x">
   <img src="fallback.png">
</picture>


See also

Node

 

 

Show: