Combining CSS media queries

2019-01-17 14:23发布

问题:

I want to display the same set of CSS styles to people printing the page (media=print) and people browsing on a mobile phone. Is there a way I can combine CSS media queries?

Something like

@media only print or @media only screen and (max-device-width: 480px) {
  #container {
    width: 480px;
  }
} 

回答1:

Separate them with a comma:

@media only print, only screen and (max-device-width: 480px)

See the spec, in particular, example VI (emphasis added):

Several media queries can be combined in a media query list. A comma-separated list of media queries. If one or more of the media queries in the comma-separated list are true, the whole list is true, and otherwise false. In the media queries syntax, the comma expresses a logical OR, while the ‘and’ keyword expresses a logical AND.

I doubt that the second only is needed, so you can probably do:

@media only print, screen and (max-device-width: 480px)


回答2:

From https://developer.mozilla.org/en/CSS/Media_queries

You can combine multiple media queries in a comma-separated list; if any of the media queries in the list is true, the associated style sheet is applied. This is the equivalent of a logical "or" operation.

You just have to remove the second @media and add some brackets.