Skip to main content

HTML <picture> Tag

The HTML <picture> tag allows displaying of different images depending on the device or screen dimensions of the user. The <picture> tag can help developers provide a better visual experience for their users, as well as improve performance by only displaying the appropriate image for each situation.

Using code snippets, we can demonstrate how to use the <picture> tag in HTML. First, we'll define where our various images can be found:

<picture>
<source media="(min-width: 800px)" srcset="https://cdn.pixabay.com/photo/2021/12/09/18/46/forest-6858884_640.jpg" >
<source media="(min-width: 500px)" srcset="https://cdn.pixabay.com/photo/2021/12/09/18/46/forest-6858884__340.jpg" >
<img src="https://cdn.pixabay.com/photo/2021/12/09/18/46/forest-6858884__340.jpg" alt = "my image" />
</picture>

In the example above, we've defined three separate images that should be displayed based on the size of the user's device—a large image (800px or wider), a medium image (500px or wider) and a small image (any width). By using this code snippet, developers can ensure that their page looks great and performs optimally on all devices without having to define multiple styles based on screen size.

The <picture> tag also has some other features and benefits that make it attractive to web developers.

  • It allows them to display entirely different images for different media types—that is, a page may have one set of visuals for desktops and another set geared specifically towards mobile users if desired.
  • Since each source element within the <picture> container is given priority over subsequent sources with lower priority values specified in its media attribute, developers can easily control which source will be used first among those with conflicting queries.
  • They can also use art direction with picture elements that contain two or more sources with different sizes to tailor an image's position within their layout on larger screens while still providing smaller devices with an appropriate scaled-down version of the same image — all without any extra coding beyond what is already present inside the <picture> tag!