<picture> element for the first time
(With the help of Pokémon)
Don’t you think it’s time we used the
<picture> element as an enchancement to responsive sites? I did too, so this week I used it for the first time.
Here’s a really really boiled down version of how to get started using it. There are much better tutorials out there but this could be useful if, like me, you spent one way too long figuring out the basics to this.
There’s not much too it, as it’s just a wrapper for the
<source> element exactly like
When implementing this on our new production site, the first thing that threw me and my team off was the
<source> elements. These are the functional parts of picture which define the different image resolutions or aspect ratios that may be more appropriate at different pixel densities or screen sizes.
srcset, not src! because
<source> supports a comma-separated list of images for different pixel densities:
<source srcset="pikachu-medium.jpg, pikachu-large.jpg 2x">
as well as the standard:
<source> accepts any valid CSS media query like:
<source media="(min-width: 800px)" srcset="pikachu-large.jpg">
Also worth noting is that the position of the source elements with their media attributes matter! If the browser comes across a
<source> that matches it’s current parameters, it will show that image and not bother checking the other sources below it.
We gotta have a Plan B
The fallback in case the browser doesn’t know what to do with the
<picture> element is
<img>. The fallback is required because it’s the place to write the alternative text for the picture and it’s the one that shows up if none of the media queries match in any of the sources.
Put it together
<picture> <source media="(min-width: 800px)" srcset="pikachu.jpg"> <img src="riachu.jpg" alt="This picture loads on non-supporting browsers"> </picture>
Resize the page to see the change!
But caniuse it?
Yes. The idea behind having the
<img> tag is that all browsers should theotically support the