Sub topic 7
Nesting @media and other at-rules
This chapter assumes you know class, type, and pseudo-class selectors, the cascade and specificity, and how to write a media query. It also assumes you have seen the & nesting selector from earlier chapters. Here you will learn how conditional at-rules behave when they sit inside a style rule, which at-rules are allowed there, and which mistakes to avoid.
What the browser does with a nested at-rule
Before native nesting, a responsive component needed its rules scattered across several media blocks. With nesting, you place the condition inside the rule it modifies:
.panel {
display: block;
@media (min-width: 40rem) {
display: grid;
grid-template-columns: 1fr 2fr;
}
}The browser treats this as if you had written the following:
.panel {
display: block;
}
@media (min-width: 40rem) {
.panel {
display: grid;
grid-template-columns: 1fr 2fr;
}
}The declarations inside @media apply to the parent selector, .panel. You do not write & around them. The condition adds no specificity. The selector is still .panel, with specificity (0,1,0), whether or not the media query matches.
Which at-rules can be nested
Only the conditional group rules can sit inside a style rule. These are the ones you will use most:
| At-rule | What the nested block does |
|---|---|
| `@media` | Applies declarations when the viewport or user preference matches |
| `@supports` | Applies declarations when the browser supports a feature |
| `@container` | Applies declarations when an ancestor container matches a size or style query |
| `@layer` | Places the nested rules in a cascade layer |
| `@scope` | Limits the rules to a DOM subtree |
| `@starting-style` | Sets the starting values for a transition on first render |
Other at-rules are not valid inside a style rule. @font-face, @keyframes, @import, and @charset stay at the top level. If you put one inside a rule, the browser drops it.
Declarations and nested rules inside an at-rule
The body of a nested at-rule can contain declarations, nested style rules, or both:
.card {
padding: 1rem;
@media (min-width: 48rem) {
padding: 2rem;
& .title {
font-size: 1.5rem;
}
&:hover {
box-shadow: 0 2px 8px rgb(0 0 0 / 0.2);
}
}
}The flat equivalent is:
.card {
padding: 1rem;
}
@media (min-width: 48rem) {
.card {
padding: 2rem;
}
.card .title {
font-size: 1.5rem;
}
.card:hover {
box-shadow: 0 2px 8px rgb(0 0 0 / 0.2);
}
}Inside the at-rule, & still means the outer parent, .card. The at-rule does not become a new parent. Everything you learned about compound selectors, combinators, and ancestor context applies unchanged.
Nesting @supports
@supports works the same way. It is useful for progressive enhancement, because the fallback sits next to the enhancement:
.gallery {
display: flex;
flex-wrap: wrap;
gap: 1rem;
@supports (display: grid) {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
}
}Browsers that understand display: grid apply the grid. Others keep the flex layout. The @supports block adds no specificity, so the grid declarations win only because they come later in source order.
Nesting @container
Container queries nest the same way, with one rule that catches many people. A container query tests an ancestor of the element, never the element itself.
.card-wrapper {
container-type: inline-size;
}
.card {
display: block;
@container (min-width: 30rem) {
display: grid;
grid-template-columns: 8rem 1fr;
}
}Here .card changes layout when .card-wrapper is at least 30rem wide. If you put container-type: inline-size on .card itself and then query inside .card, the query matches no container. It looks for an ancestor with container-type, and .card is not its own ancestor.
You can name a container with container-name and target it in the query: @container sidebar (min-width: 20rem). This helps when several ancestors are containers and you want a specific one.
Nesting @layer
A nested @layer block puts the rule into a named cascade layer, with the parent selector wrapped around it:
@layer reset, components, utilities;
.btn {
@layer components {
padding: 0.5rem 1rem;
background: #0a58ca;
color: white;
}
@layer utilities {
&.is-wide {
width: 100%;
}
}
}This is the same as writing @layer components { .btn { ... } } and @layer utilities { .btn.is-wide { ... } } at the top level. The first line declares the layer order so the result does not depend on which nested block the browser meets first. Without that line, layers are ordered by first appearance, and a nested layer can end up in a different position than you expect.
Layers matter more than specificity in the cascade, so a rule in a later layer beats a rule in an earlier layer even when the earlier rule has a more specific selector.
Stacking at-rules
You can nest at-rules inside each other, and the conditions combine as if joined with "and":
.sidebar {
display: none;
@media (min-width: 60rem) {
@supports (position: sticky) {
display: block;
position: sticky;
top: 1rem;
}
}
}The sidebar appears only when the viewport is at least 60rem wide and the browser supports position: sticky. Keep stacks shallow. Two levels is readable, and three usually means the rule should be split up.
Mixing declarations, nested rules, and at-rules
Declarations can appear before or after nested rules and at-rules. The order of the declarations among themselves still follows the usual cascade rules, but a declaration written after a nested block is not "moved" above it. Consider this example:
.box {
color: black;
@media (min-width: 40rem) {
color: navy;
}
color: crimson;
}At narrow widths the text is crimson, because the last color wins. At 40rem or wider the text is still crimson. The media block is positioned between the two declarations. The later color: crimson comes after the media rule in source order and has the same specificity, so it overrides the media rule. Modern browsers handle this correctly, but older implementations hoisted all the plain declarations to the top. To avoid surprises, put all of a rule's own declarations first, then its nested rules and at-rules.
Common errors
- Wrapping the declarations in
& { }without need. Declarations directly inside a nested conditional at-rule are valid. Wrapping them adds nothing. - Putting
@keyframesor@font-faceinside a rule. These are dropped. Keep them at the top level. - Querying a container from the container itself. The query matches nothing, as shown above.
- Expecting
@mediato raise specificity. It does not. If a media-scoped rule loses, the cause is source order, a more specific selector elsewhere, or a layer. - Assuming Sass-style output. Sass can build selectors by string concatenation, and native nesting cannot. Native nesting resolves the parent as a whole selector, which the next chapters on Sass differences cover in more detail.
- Using
@mediain a selector list parent and expecting separate behavior. If the parent is#main, .note, the nested media rule applies to the parent as:is(#main, .note). Specificity follows the most specific item in the list, as covered in the specificity chapter.
A realistic example
This component combines several of the pieces above:
@layer base, components;
.nav-wrapper {
container-type: inline-size;
}
.nav {
@layer components {
display: flex;
flex-direction: column;
gap: 0.5rem;
a {
padding: 0.5rem;
}
@container (min-width: 36rem) {
flex-direction: row;
gap: 1rem;
}
@media (prefers-reduced-motion: no-preference) {
a {
transition: background-color 150ms ease;
}
}
@media (prefers-color-scheme: dark) {
background: #222;
color: #eee;
}
}
}The .nav rule lives in the components layer. It stacks vertically in a narrow container and switches to a row in a wider one. Link transitions are enabled only for users who have not asked for reduced motion. Dark colors apply only under a dark color scheme. All the conditions sit beside the rules they change, and each is easy to find by scanning the component.
Browser support note
Nested conditional at-rules arrived with native nesting in current versions of the major browsers. A browser that does not understand nesting ignores the whole nested block, including the at-rule inside it. If you must support those browsers, keep the base styles flat and add the nested enhancements on top, or compile with a build step.
Exercise
Rewrite the nested CSS below as flat CSS with the same behavior. Then say which selector would match if the screen is 50rem wide, and what its specificity is. .tile { color: gray; @media (min-width: 40rem) { color: black; &:hover { color: blue; } } }
Show answer
Flat version:
.tile {
color: gray;
}
@media (min-width: 40rem) {
.tile {
color: black;
}
.tile:hover {
color: blue;
}
}
At 50rem the media query matches, so .tile gets color: black and .tile:hover gets color: blue on hover. Specificity of .tile is (0,1,0), the same as without the media query, because @media adds nothing. Source order lets the later .tile rule win. Specificity of .tile:hover is (0,2,0).
Exercise
A .card rule sets container-type: inline-size and also contains a nested @container (min-width: 30rem) { ... } block that should restyle .card. The block never applies. Why, and how do you fix it?
Show answer
A container query matches an ancestor container, never the element itself. .card is both the container and the target, so no matching container is found. Move container-type: inline-size to a parent element (for example .card-wrapper), and keep the nested @container block inside .card.