23
loading...
This website collects cookies to deliver better user experience
@supports () { ... }
, but that doesn't work for media queries. In this article I'll show you how you can.prefers-reduced-data
I wanted to apply something in one of two situations:prefers-reduced-data
at allprefers-reduced-data
and the value was "no-preference".@media (prefers-reduced-data: no-preference)
because that would be false if either there was no support (since the browser wouldn't understand the media query) or if it was supported but the user wanted to preserve data.@media not all and (prefers-reduced-data), (prefers-reduced-data) {
...
}
not all and
. "all" is the default media type, and it applies to both screen
and print
. You can omit it (and likely you usually do), but if you add it you need to add "and" in between it and the media feature (which is the part between parentheses). not
is how you can negate a media query. For example, @media not print {...}
would apply everywhere except print.all
being the default, what we're really checking here for is "not (prefers-reduced-data)". Unfortunately that's invalid notation until supports for Media Queries level 4 lands, so we need to add the "all and" here.not all and (prefers-reduced-data)
: false(prefers-reduced-data)
: falsenot all and (prefers-reduced-data)
: true(prefers-reduced-data)
: falsenot all and (prefers-reduced-data)
: false(prefers-reduced-data)
: truewindow.matchMedia
API:const isSupported = window.matchMedia(
`not all and (prefers-reduced-data), (prefers-reduced-data)`
).matches;
const query = '(prefers-reduced-data)';
const resolvedMediaQuery = window.matchMedia(query).media;
const isSupported = query === resolvedMediaQuery;
window.matchMedia
api also returns a "media" property, which is the normalized and resolved string representation of the query you tested. If matchMedia encounters something it doesn't understand, that changed to "not all", and if it does support the query it will return that, regardless of if it matches (you can use the matches property for that).(prefers-reduced-data )
(notice the space), that would resolve "matches" to true in supported browsers because the white space is not important, but comparing the normalized media query would return false, since that normalization has removed that extra space. So string comparison can be tricky depending on your input.prefers-reduced-data
, prefers-contrast
, screen-spanning
and more.