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
- Better Line Breaks With CSS balance and pretty
Use text-wrap balance for short headings and text-wrap pretty selectively for longer copy without hard-coded line breaks.
- Why 100vh Doesn’t Always Fit a Mobile Screen
Choose svh, lvh, dvh, or a flexible min-height when mobile browser controls make 100vh an awkward fit.
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.