How to Combine Media Queries in CSS: Syntax and Examples
You can combine media queries in CSS using
and, or (comma), and not operators inside the @media rule. Use and to require multiple conditions, commas to separate alternative queries, and not to exclude conditions.Syntax
The @media rule lets you combine conditions using:
and: All conditions must be true.- Comma (,): Acts like or, any condition can be true.
not: Negates a condition.
Example: @media (min-width: 600px) and (max-width: 900px), (orientation: landscape)
css
@media (min-width: 600px) and (max-width: 900px), (orientation: landscape) { /* CSS rules here */ }
Example
This example changes the background color when the screen width is between 600px and 900px or when the device is in landscape mode.
css
body {
background-color: lightgray;
}
@media (min-width: 600px) and (max-width: 900px), (orientation: landscape) {
body {
background-color: lightblue;
}
}Output
The page background is lightgray by default. It changes to lightblue if the screen width is between 600px and 900px or if the device is in landscape orientation.
Common Pitfalls
Common mistakes include:
- Using commas when you mean
and, which changes logic from all conditions to any condition. - Forgetting parentheses around each condition.
- Using
orkeyword (which is invalid in CSS).
Correct use:
css
/* Wrong: uses 'or' which is invalid */ /* @media (min-width: 600px) or (max-width: 900px) { ... } */ /* Right: use comma for 'or' */ @media (min-width: 600px), (max-width: 900px) { /* CSS rules */ } /* Right: use 'and' for combining conditions */ @media (min-width: 600px) and (max-width: 900px) { /* CSS rules */ }
Quick Reference
| Operator | Meaning | Example |
|---|---|---|
| and | All conditions must be true | @media (min-width: 600px) and (max-width: 900px) { ... } |
| , (comma) | Any condition can be true (logical OR) | @media (orientation: portrait), (orientation: landscape) { ... } |
| not | Negates a condition | @media not all and (monochrome) { ... } |
Key Takeaways
Use
and to combine multiple conditions that must all be true.Use commas to separate media queries acting like OR conditions.
Never use the word
or in media queries; use commas instead.Always wrap each condition in parentheses for clarity and correctness.
Use
not to exclude specific conditions in media queries.