Search code examples
htmlcssmedia-queries

How do I nest and/or statements in a CSS media query?


I want to do a media query that says:

only screen and either
    (max-width: 64em) and (min-width: 24em)
        or
    (orientation: landscape)

In JavaScript notation, what I want would look like this:

if ( screen === true && ( width > 24 && width < 64 ) || orientation === "landscape" )

How do I do that? Can I use parentheses? Would it be:

<link 
    rel='stylesheet' 
    media='only screen and ( ((max-width: 64em) and (min-width: 24em)) or (orientation: landscape) )' href='style.css' />

Is this even possible?


Solution

  • "or" is expressed with a comma separating two or more entire media queries; "and" with the and keyword within each media query separating each condition.

    Any condition that should hold true for all media queries must be repeated within each query; in your case, that common condition is only screen.

    Thus:

    only screen and (max-width: 64em) and (min-width: 24em), 
    only screen and (orientation: landscape)
    

    If you need to use this media query in a CSS @media at-rule rather than an HTML media attribute, note that the @media token appears only once as it's not technically part of a media query:

    @media only screen and (max-width: 64em) and (min-width: 24em), 
           only screen and (orientation: landscape)
    {
    }