<picture>
The <picture>
tag is a wrapper for one <img> and several <source> tags. It aims to handle multiple images, so that the browser can display the best one for the current layout or screen size. For example, thanks to it you can display larger images for high resolution screens. Unlike <audio> and <video> tags, the <picture>
tag accepts only sources specified via srcset
attribute.
For example, you can display one-pixel red dot if the screen is wider than 1px:
<picture>
<source media="(min-width:1px)" srcset="//static.base64.guru/uploads/images/1x1.gif" />
<img src="about:blank" />
</picture>
The same can be achieved by encoding image to Base64 and embedding it using data URI:
<picture>
<source media="(min-width:1px)" srcset="data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs" />
<img src="about:blank" />
</picture>
Both behaviors are identical — when you open the page, your browser displays the same image specified within <source>
tag. The difference is that in the first case the browser sends one HTTP request to fetch the external image, when in the second case the image is already loaded in the browser’s memory and it does not need to send any HTTP requests.
Please note that Base64 Data URIs have some limitations. In addition, like almost any unconventional solutions, it has both advantages and disadvantages. Therefore, if you plan to use it, first of all, read about Base64 Data URI.
Comments (11)
I hope you enjoy this discussion. In any case, I ask you to join it.