GIFS and prefers-reduced-motion

Avatar of Chris Coyier
Chris Coyier on

The <picture> element has a trick it can do where it shows different image formats in different situations. If all you are interested in is formats for the sake of performance, maybe you’d do:

<picture>
  <source srcset="img/waterfall.avif" type="image/avif">
  <source srcset="img/waterfall.webp" type="image/webp"> 
  <img src="img/waterfall.jpg" alt="A bottom-up shot of a huge waterfall in Iceland with green moss on either side.">
</picture>

But notice those <source> elements there… they can take a media attribute as well! In other words, they can be used for responsive images in the sense that you can swap out the image for a different one, perhaps even one with a different aspect ratio (e.g. a wide-crop rectangle shape on a large screen vs. close-crop square shape on a small screen).

The media attribute doesn’t have to be screen-size related though. Brad Frost documented this trick a while back:

<picture>
  <source srcset="no-motion.jpg" media="(prefers-reduced-motion: reduce)"></source> 
  <img srcset="animated.gif" alt="brick wall">
</picture>

That is using a prefers-reduced-motion media query to swap a GIF for a static image when less movement is preferred (a system-level choice). Clever! I saw Manuel’s tweet about it get some love the other day:


Remember our little rif on Steve Faulkner’s idea from a little while ago? Rather than entirely stopping the GIF, you can put animated and non-animated images on top of each other (inside a <details> element) and allow them to be “played” on demand. We could alter that a smidge again and have it respect this media query by using a smidge of JavaScript: