Halloween Man
Halloween Man

Reputation: 89

How can I invert a media query using the NOT operator?

How would I invert the following media query? I.e. not (A or B), alternatively not A and not B:

@media only screen and (max-width: 512px), only screen and (max-height: 512px) { }

Simply doing @media screen and not (max-width: 512px), screen and (max-height: 512px) { } does not work.

Upvotes: 2

Views: 1574

Answers (2)

TylerH
TylerH

Reputation: 21074

Note—this currently does not work in Chrome or Chromium-based browsers, as it relies on features in Media Queries Level 4 which Chrome has yet to implement.

You would achieve your desired outcome, based on the code you've provided, by wrapping the conditions you want inside another set of parentheses.

In this demo, the red background in the media query applies all the time except when the conditions are met. So whenever the screen is below 500px in width and height, the conditions aren't met, and the original styles apply.

.container {
    width: 500px;
    height: 500px;
    background: green;
}

@media screen and not ((max-width:500px) or (max-height: 500px)) {
    .container {
        background: red;
        width: 200px;
        height: 200px;
    }
}
<div class="container">
    <p>
    This is some text!
    </p>
</div>

Be aware that not screen is probably not what you want, since that means it won't ever apply on a computer screen. In Media Queries Level 3, however, that is the required and only supported location to put the not keyword (to negate an entire query).

Upvotes: 1

Halloween Man
Halloween Man

Reputation: 89

Thanks to @disinfor and @TylerH

@media only screen and (min-width: 513px) and (min-height: 513px) {}

does the trick

Upvotes: 1

Related Questions