How to combine multiple "groups" of CSS media queries?

446 Views Asked by At

In CSS Media queries, you can use , (for "or") and and to match media query requirements. For example:

@media (min-width: 768px) and (min-resolution: 2dppx) { ... }

But what if you wanted to mix and and , in the same media query? A good use case would be that min-resolution is not supported in all browsers. You have to do something like this:

@media
(-webkit-min-device-pixel-ratio: 2),
(min-device-pixel-ratio: 2),
(min-resolution: 192dpi),
(min-resolution: 2dppx) { ... }

In this case, ANY of those requirements need to match for the media query to take effect.

So now, if I wanted to also require the min-width: 768px in the media query how would I do this? Is it possible to group the "or" queries together and separate the group with an and? Something like this:

@media
(
  (-webkit-min-device-pixel-ratio: 2),
  (min-device-pixel-ratio: 2),
  (min-resolution: 192dpi),
  (min-resolution: 2dppx)
)
and
(min-width: 768px) { ... }

The above syntax does not work, but I think it maybe illustrates what I'm trying to get at. It would be sort of like how you group SQL AND and OR queries together using (...) parenthesis.

Is it possible to do this with CSS?

EDIT:

This seems to work but it seems like syntax overkill:

@media
  (-webkit-min-device-pixel-ratio: 2) and (min-width: 768px),
  (min-device-pixel-ratio: 2) and (min-width: 768px),
  (min-resolution: 192dpi) and (min-width: 768px),
  (min-resolution: 2dppx) and (min-width: 768px)
  { ... }

Is that the only way to do it?

1

There are 1 best solutions below

2
On

Try using it like this :

@media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi), (min-resolution: 2dppx) and (min-width: 768px) {...}

, is interpreted as the delimiter in a list of single media queries basically meaning each media query between the commas is first evaluated, then all of them are ORed together thereby giving the , / OR the lowest precedence.

and has the highest precedence