I am planning to start using HTML picture tags on my website. I know that with picture tags, it is possible to use media queries and serve differently-sized images and different file formats. But are the following things possible?
The <picture>
element can be used to provide alternative sources for an image. It must have a default <img>
element.
From top to bottom, the first matching and supported <source>
element's source will be used instead of the fallback image's. If you want to prefer WebP over JPEG, simply list the WebP <source>
s first:
<picture>
<source srcset="alternative.webp" type="image/webp">
<source srcset="alternative.jpeg" type="image/jpeg">
<img src="default.png">
</picture>
As for querying against the container: I believe this is currently not possible.
Ideally, the page is designed in a way where you (as the designer) know how the elements will be sized. If this is not the case, you can still estimate what sources to serve for certain sizes.
I highly recommend to read MDN's Responsive images article. In short, you should use the following:
srcset
: A list of all alternative sources along with either their intrinsic widths or pixel density descriptors only.sizes
: A list of media queries and the resulting slot sizes.Note: The px
unit in the sizes
attribute refers to "CSS pixels". These CSS pixel don't refer to actual device pixel; they refer to virtual pixels that are scaled to be reasonably sized for the device. (Related: The Viewport meta tag.)
The browser will calculate which source to use based on the source's and the slot's size, while considering the scale between device and CSS pixels.
Or in other words: With the information given via the attributes, the browser will choose the highest-quality image for your media (i.e. screen).
At a glance, I also found the blog Responsive images by KeyCDN informative.