The Picture Elements

HTML Tutorial

HTML Forms

HTML Graphics

HTML Media

HTML API

The Picture Element

HTML <picture> Element

The HTML <picture> element allows to display different pictures for different devices or screen sizes.

The HTML <picture> Element

The HTML <picture> element provides web developers the flexibility to specify image resources at an ease.

The <picture> element consists of one or more <source> elements, each referring to different images through the srcset attribute. This allows the browser to choose the image that best fits the current view and/or device.

Each <source> element has a media attribute , specifying when the image is the most suitable.

				
					<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>The picture Element</h2>
<picture>
  <source media="(min-width: 650px)" srcset="img_food.jpg">
  <source media="(min-width: 465px)" srcset="img_car.jpg">
  <img decoding="async" src="img_girl.jpg" style="width:auto;">
</picture>
<p>Resize the browser to see different versions of the picture loading at different viewport sizes.
The browser looks for the first source element where the media query matches the user's current viewport width,
and fetches the image specified in the srcset attribute.</p>
<p>The img element is required as the last child tag of the picture declaration block.
The img element is used to provide backward compatibility for browsers that do not support the picture element, or if none of the source tags matched.
</p
<p><strong>Note:</strong> The picture element is not supported in IE12 and earlier or Safari 9.0 and earlier.</p>
</body>
</html>


				
			

When to use the Picture Element

There are two main uses of the element:

1) Bandwidth

For a  small screen or device, it is not necessary to load a large image file. The browser firstly uses the element with matching attribute values and ignores any of the following elements.

2) Format Support

Some browsers or devices do not support all image formats. By using the element, images of all formats can be added, and the browser will use the first format it recognizes, and ignore any of the following elements.

Example:

The browser will use the first image format it recognizes: