Sub topic 5
Combining conditions with and, comma, and not
This chapter assumes you can write a basic @media rule with min-width or max-width. It also assumes you know how the cascade resolves conflicting rules and how em units relate to font size. Here you will combine several conditions in one query.
and: every condition must be true
The and operator joins conditions. The rule applies only when all of them hold.
@media screen and (min-width: 30em) and (max-width: 59.99em) {
.sidebar {
display: none;
}
}This rule applies only on screens between 30em and just under 60em wide. If you include a media type such as screen, it must come first. Each condition goes in its own parentheses, and and needs whitespace on both sides.
The 59.99em upper bound avoids an overlap. Both max-width: 60em and min-width: 60em are true at exactly 60em, so the two rules would apply together there.
comma: any query may match
A comma separates complete queries, and the rule applies if at least one of them matches. It works like a logical "or".
@media (max-width: 20em), print {
.promo {
display: none;
}
}The promo is hidden on very narrow viewports and also when printing. Each part of a comma list is evaluated independently, so each one needs to be a full, valid query.
not: negate a query
The not keyword inverts the result of a query.
@media not print {
.print-note {
display: none;
}
}not must appear at the start of a query. It negates the whole query that follows, not just the part next to it.
In a comma list, not applies only to its own query. In @media not print, (min-width: 50em), the second query is evaluated separately.
How the browser evaluates a query list
Summary of the operators
| Operator | Meaning | Example |
|---|---|---|
| `and` | All conditions must match | `screen and (min-width: 30em)` |
| `,` | At least one query must match | `(max-width: 20em), print` |
| `not` | Inverts the whole query | `not print` |
Common errors
- Using a comma where you need
and.(min-width: 40em), (max-width: 20em)matches every width except the range between 20em and 40em. To require both conditions, useand. - Placing
notin the middle of a query.screen and not (color)is invalid in a basic query. Putnotfirst. - Forgetting parentheses.
min-width: 30emwithout parentheses is invalid. Wrap each condition in parentheses. - Leaving gaps or overlaps between ranges. Check what happens at the exact boundary value.
Exercise
What does @media (max-width: 30em), (orientation: landscape) match, and how would you change it so both conditions must be true?
Show answer
It matches when the viewport is at most 30em wide, or when it is in landscape orientation, or both, because the comma means "or". To require both, replace the comma with and: @media (max-width: 30em) and (orientation: landscape).