Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I learned a small trick about CSS media queries that can help to save some bytes on the wire. You might know that you can check for user preferences using media queries.

Let's take the prefers-reduced-motion media query as an example.๐Ÿ‘‡

@media screen and (prefers-reduced-motion: reduce) {
  /* stop all these animations */
}

You can use the prefers-reduced-motion query to stop animating elements when users prefer not to see motion and animations (learn more about why you should do that on CSS-Tricks). The query can have two different values: no-preference and reduce.

If you have used this media query before, you might know that you can also use its short variant and drop the reduce value. The media query will behave the same.

@media screen and (prefers-reduced-motion) {
  /* stop all these animations */
}

And what you see there is the media query's boolean context in action. The spec defines the no-preference value as follows:

[no-preference] indicates that the user has made no preference known to the system. This keyword value evaluates as false in the boolean context.

This definition means that when you're using the shorthand media query without defining a value, everything other than no-preference will evaluate to true.

A boolean context might seem obvious for prefers-reduced-motion because it allows only two different values, but there are also media queries with more than two options. And today I learned, that these can implement a boolean context, too.

Look at prefers-contrast โ€“ this media query allows four different values: no-preference, less, more and custom. And while there are four available options; no-preference evaluates to false and every other value to true.

/* evaluates to true for `less`, `more` and `custom` */
@media screen and (prefers-contrast) { }

Boolean contexts allow you to shorten your media queries and come in handy when you only want to check for a non-default value. If you want to learn more about them, read the boolean context spec.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles