Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest media queries within media queries?

Is this possible? It seems like a neat solution to me, but I'm not sure if it will work.

@media only screen  and (min-device-width : 320px)  and (max-device-width : 480px) {      /* Code for both portrait and landscape */      @media (orientation:portrait) {          /* Code for just portrait */      }      @media (orientation:landscape) {          /* Code for just landscape */      }  } 
like image 237
SparrwHawk Avatar asked Oct 05 '11 22:10

SparrwHawk


People also ask

Can I put a media query inside a media query?

Yes, you can, and it doesn't really matter in what order. A CSS preprocessor is not required. It works in regular CSS. There is probably a point where the logic of that gets out of hand, so careful.

Can media queries overlap?

If you wish to avoid overlap, you simply need to write media queries that are mutually exclusive. Remember that the min- and max- prefixes mean "minimum inclusive" and "maximum inclusive"; this means (min-width: 20em) and (max-width: 20em) will both match a viewport that is exactly 20em wide.

How do I merge two media queries?

Each media feature expression must be surrounded by parentheses. Logical operators can be used to compose a complex media query: not , and , and only . You can also combine multiple media queries into a single rule by separating them with commas.


2 Answers

You should be able to nest @media rules this way in CSS3, but it isn't yet supported by most browsers. See this answer for details.

You would have to fully expand and repeat the top-level media queries for the inner rules for it to work across browsers (and I imagine the SCSS processor would generate something similar):

@media only screen  and (min-device-width: 320px)  and (max-device-width: 480px) {     /* Code for both portrait and landscape */ }  @media only screen  and (min-device-width: 320px)  and (max-device-width: 480px)  and (orientation: portrait) {      /* Code for just portrait */  }  @media only screen  and (min-device-width: 320px)  and (max-device-width: 480px)  and (orientation: landscape) {      /* Code for just landscape */  } 
like image 166
BoltClock Avatar answered Sep 19 '22 21:09

BoltClock


If you wanted to do this the best way is to use the high level media query in a link tag, and then the other queries inside the linked sheet.

In practice though most people cascade their CSS rules from a base sheet that covers the common stuff and then putting changes to that in each media rule-set.

like image 44
Richard Hulse Avatar answered Sep 19 '22 21:09

Richard Hulse