As we previously saw, the image (img) tag is easy to use, however, as more and more people view websites on tablets, phones, and other devices besides a computer, we have to be mindful of how images will appear to those users.
In CSS we can use responsive design, which adjusts the layout based upon the screen resolution. However we can’t necessarily specify the image to be used in CSS. We can change the size, but we don’t want to download a large image and resize it, especially on a mobile network.
Therefore, we use the picture tag where we can specify different images based upon the screen resolution of the user. This gives the web developer more flexibility when designing the page, and selecting the image.
To use the <picture>
tag, you will have several required children tags. First, is a <source>
tag. One or more of these will be used, and you will have your final <img>
tag which is used like a standard image tag. The <img>
tag should be the last one in the list of child tags, and is used for backward compatibility in case the browser doesn’t understand <source> tags.
<source> tag
The <source> tag is used to define what the image source will be, since we will be listing multiple images. There are multiple attributes to the source tag, but these are the ones you’ll use most often.
- srcset (required) – defines the URL of the image that will be displayed
- media – accepts any valid media query that would normally be defined in a CSS eg: media=”(min-width: 465px)”
Based upon the source attributes, the browser will pick the best option and ignore other source options to display.
The source tag can be used for other tags as well, and has other attributes to assist when it is being used for video or audio applications, however, we’re going to focus on the image usage here.
<picture>
<source media="(min-width: 650px)" srcset="large_flowers.jpg">
<source media="(min-width: 465px)" srcset="medium_flower.jpg">
<img src="small_flowers.jpg" alt="Flower Arrangement">
</picture>
Picture Tag was originally found on Access 2 Learn