User preference feature queries have a boolean context
- Published at
- Updated at
- Reading time
- 2min
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.
Join 5.5k readers and learn something new every week with Web Weekly.