Picture HTML

HTML <picture> Tag

In responsive web designing, it is required to load different images based on their viewport, height, width, orientation, and pixel density, and this is where the HTML <picture> tag is used. It was introduced in HTML5. Multiple <source> elements and an <img> elements can be placed inside an HTML <picture> element. The matching image will thus be loaded, according to the viewport. The default image defined within the <img> tag is displayed when no source contains the matching image. In more simple words, the HTML <picture> element is used to make an image responsive. It sets more than one image depending on the browser width. The picture changes when the size of the browser changes.

Syntax:

<picture>
<source srcset="" media="">
<img src="">
</picture>

Example:

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Resize the browser width to see the effect.</h2>
<picture>
  <source srcset="img_1.jpg" media="(max-width: 600px)">
  <source srcset="img.jpg" media="(max-width: 1500px)">
  <source srcset="img_2.jpg">
  <img src="img.jpg" alt="Flowers" style="width:auto;">
</picture>
</body>
</html>

Explanation:

In the above example, we made an image responsive, using the HTML <picture> element.

Tag specific attributes:

Attribute Value Uses
media media_query Used to specify and to add a media query to be defined in CSS.
srcset URL Used to specify the image URL. It is a required attribute.
type video/ogg

video/mp4

video/webM

audio/ogg

audio/mpeg

Used to indicate the MIME type.
src URL Used to indicate the location of the image.

Global attributes:

The HTML global attributes are supported by the HTML <picture> tag.

Event attributes:

The HTML event attributes are supported by the HTML <picture> tag.

Supporting Browsers:

Chrome, IE, Firefox, Opera, and Safari.