/

The HTML `picture` tag: A Guide to Responsive Images

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
2
3
4
<picture>
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="An image">
</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
2
3
4
5
6
7
<picture>
<source media="(min-width: 500w)" srcset="dog-500.png" sizes="100vw">
<source media="(min-width: 800w)" srcset="dog-800.png" sizes="100vw">
<source media="(min-width: 1000w)" srcset="dog-1000.png" sizes="800px">
<source media="(min-width: 1400w)" srcset="dog-1400.png" sizes="800px">
<img src="dog.png" alt="A dog image">
</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”]