Nesting Media Queries in CSS
CSS media queries can be nested when they are both at the root of the stylesheet. This is useful when two separate conditions need to match before a rule applies.
Here is the smallest example:
@media not print {
@media (min-width: 0) {
p {
background: blue;
}
}
}
The paragraph gets a blue background only when both queries match: the output is not being printed, and the viewport is at least 0 pixels wide. That second condition is deliberately simple, but it shows how the queries are combined.
This is different from placing an @media rule inside a normal selector. For straightforward conditions, I would usually put them in one query with and; it is easier to read. Nesting is most useful when an outer query already groups a larger set of related rules.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.
- When CSS Layout Order Stops Matching the HTML
Keep Grid and Flexbox layouts aligned with the HTML order so keyboard focus and screen reader reading do not jump around the page.
- Keyboard Focus Styles With :focus-visible
Keep a clear keyboard focus indicator while avoiding the same focus ring after every pointer interaction.