/

HTML / CSS / JavaScript Tutorial

HTML Element: <picture>

[this page | pdf | back links]

The HTML <picture> element indicates a container for multiple image resources. A <picture> element contains zero or more <source> elements followed by one <img> element. The source element(s) will be differentiated by different srcset attributes (required, defines the URL of the image to be shown by the <picture> element) and by the media attribute (optional, a CSS media query that identifies which media relates to that URL). The browser uses the first matching <source> element, and if none match then it defaults to the <img> element.

 

The attributes it can take are HTML global attributes and HTML event attributes.

 

To create or access such an element in JavaScript see here. The corresponding HTML DOM object supports standard DOM properties and methods. The default style applicable to this element is shown here.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
Created using HTML:<br>
If media width is >= 600px then will show 2 shapes, otherwise just 1<br>
<picture>
  <source srcset="Pictures/Shape1and2.png" media="(min-width: 600px)">
  <img src="Pictures/Shape1.jpg" alt="picture not recognised by browser">
</picture>

<br><br>Created using JavaScript:<br>
<span id="element"></span>

<script>
var x = document.createElement("PICTURE")
var x1 = document.createElement("SOURCE");
var x2 = document.createElement("IMG");
x1.setAttribute("srcset","Pictures/Shape1and2.png");
x1.setAttribute("media","(min-width: 600px)");
x.appendChild(x1);
x2.setAttribute("src","Pictures/Shape1.jpg");
x2.setAttribute("alt","picture not recognised by browser");
x.appendChild(x2);
document.getElementById("element").appendChild(x);
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | HTML Elements


Desktop view | Switch to Mobile