HTML <picture> Tag
<picture> element is a container which provides multiple sources to its contained
img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors.
<picture> element itself does not display anything. Rather, it simply provides a context for its contained
img element that enables it to choose from multiple URLs.
<picture> element is written as
/picture, with zero or more
source elements, followed by one
img element, optionally intermixed with script-supporting elements (e.g.
The way it works is, the
img element provides the fallback image source (via its
src attribute). The
source element allows you to specify multiple alternative source sets for
img element, based on the screen pixel density, viewport size, image format, and other factors. If none of those suit the situation, then the fallback image (supplied by the
img tag) is displayed.
Here's an example to demonstrate.
Click the two orientation buttons at the top right of the editor to toggle the two images. Those two buttons change the orientation of the editor/preview pane, and therefore the width of the viewport. This in turn, causes the image from the
source element to be loaded instead of the one from the
You may need to resize your screen to see the effect. Alternatively you can adjust the code to use a more suitable width for your device (i.e. change
600px to a different value).
If the image changes between two different photos when you toggle the buttons, then you're seeing the intended effect.
Here's another example that illustrates a more realistic use case:
In this case, all image sources are based on the same photo. They just use different sizes and croppings.
Syling the Image
In this example, I used CSS to add a border to the
If you toggle the two images, you'll see that they both have the same black border as applied to the
Attributes can be added to an HTML element to provide more information about how the element should appear or behave.
<picture> element accepts the following attributes.
The following attributes are standard across all HTML elements. Therefore, you can use these attributes with the
<picture> tag , as well as with all other HTML tags.
For a full explanation of these attributes, see HTML 5 global attributes.
Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain "event" occurs. Each event handler content attribute deals with a different event.
Most event handler content attributes can be used on all HTML elements, but some event handlers have specific rules around when they can be used and which elements they are applicable to.
For more detail, see HTML event handler content attributes.