Nested media
Learn to use nesting inside @media.
Nested @media
A @media block can sit inside a selector. When you write .grid { @media (max-width: 600px) { grid-template-columns: 1fr; } }, the browser hoists it out and applies @media (max-width: 600px) { .grid { grid-template-columns: 1fr; } }.
The result is the same, but the style stays close to the component. You no longer hunt for the small-screen behavior far from the definition.
Responsive next to the component
Nested @media keeps a component's responsive behavior with its definition. If you place @media (max-width: 600px) inside the .cart block, the small-screen and large-screen forms live in one place.
You jump around the file less. When you build a component library, each component becomes self-contained.
Exercise Single column on small screens
Add a @media (max-width: 600px) block inside the .grid selector and put grid-template-columns: 1fr inside it.
Show example solution
Add a @media block inside .grid.
Example solution:
/* add @media inside .grid */
.grid {
grid-template-columns: 1fr 1fr;
@media (max-width: 600px) {
grid-template-columns: 1fr;
}
}
Theme preferences nested
The same pattern works for user preferences like prefers-color-scheme. Writing .card { @media (prefers-color-scheme: dark) { background: #111; color: #eee; } } turns the card dark automatically when the user picks a dark theme.
The component carries its own dark variant inside. A separate .dark .card selector is no longer needed.
Test yourself
-
Which snippet shows nested @media?
- @media { .grid { } } (max-width: 600px)
- .grid { @media { grid-template-columns: 1fr; } }
- @media (max-width: 600px) .grid { }
- .grid { @media (max-width: 600px) { grid-template-columns: 1fr; } }
Show answer
.grid { @media (max-width: 600px) { grid-template-columns: 1fr; } } — Correct. The @media block sits inside .grid with its own condition and curly braces.
-
Complete the condition
.grid { @media ____ { grid-template-columns: 1fr; } }Show answer
.grid { @media (max-width: 600px) { grid-template-columns: 1fr; } }