The HTML `picture` tag
Discover the basics of working with images and the HTML `picture` tag, and how to make them responsive
HTML gives us the picture tag, which does a very similar job of the srcset attribute of an img tag, and the differences are very subtle.
You use picture when instead of just serving a smaller version of a file, you completely want to change it. Or serve a different image format.
The best use case I found is when serving a WebP image, which is a format still not widely supported. In the picture tag you specify a list of images, and they will be used in order, so in the next example, browsers that support WebP will use the first image, and fallback to JPG if not:
<picture>
<source type="image/webp" srcset="image.webp">
<img src="image.jpg" alt="An image">
</picture>
The
sourcetag defines one (or more) formats for the images. Theimgtag is the fallback in case the browser is very old and does not support thepicturetag.
In the source tag inside picture you can add a media attribute to set media queries.
The example that follows kind of works like the above example with srcset:
<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>
But that’s not its use case, because as you can see it’s much more verbose.
The picture tag is recent but is now supported by all the major browsers except Opera Mini and IE (all versions).
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.