The HTML picture
tag: A Guide to Responsive Images
Discover the basics of working with images and learn how to make them responsive using the HTML picture
tag.
HTML provides us with the picture
tag, which serves a similar purpose as the srcset
attribute of the img
tag, but with subtle differences.
The picture
tag is ideal when you need to completely change an image or serve a different image format. One common use case is when serving WebP images, a format that is not widely supported yet. With the picture
tag, you can specify a list of images, and browsers that support WebP will use the first image, falling back to JPG if necessary:
1 | <picture> |
The source
tag within the picture
tag defines one or more formats for the images, while the img
tag acts as the fallback for older browsers that do not support the picture
tag.
For more versatility in image selection, you can add a media
attribute to the source
tag inside the picture
tag. This allows you to define media queries for different images, similar to the srcset
attribute:
1 | <picture> |
However, keep in mind that this use case can be more verbose compared to using the srcset
attribute alone.
The picture
tag is a relatively recent addition to HTML, but it is now widely supported by all major browsers except Opera Mini and IE (all versions).
tags: [“HTML”, “picture tag”, “responsive images”, “srcset”, “image formats”, “WebP”, “media queries”]