π What Are @media Nested Rules?
With modern CSS Nesting, you can write @media queries inside a selectorinstead of scattering them across your stylesheet. This keeps component styles grouped together, clean, and easy to maintain.
Note
β Works only when the outer rule is a valid selector
β Keeps responsive styles next to their base styles
π¦ Basic Syntax
Simply place @media inside a rule block:
Basic Nested @media
.card {
padding: 1rem;
@media (max-width: 600px) {
padding: 0.5rem;
}
}The media query adjusts the style only inside .card. This keeps all card-related CSS together.
π Why Use Nested Media Queries?
- Organizes component styles in one place
- Reduces CSS file fragmentation
- Improves readability in large projects
- Follows the philosophy of component-driven CSS
π― Example: Responsive Component
Responsive Card Component
.profile-card {
width: 300px;
padding: 1rem;
@media (max-width: 500px) {
width: 100%;
padding: 0.75rem;
}
}π Using Multiple @media Queries
Multiple Breakpoints
.hero {
font-size: 2rem;
@media (max-width: 900px) {
font-size: 1.7rem;
}
@media (max-width: 600px) {
font-size: 1.3rem;
}
}Each breakpoint adjusts the same component in a clean, stacked way.
π Combining @media with &
Use & inside @media when referencing the parent selector explicitly.
& inside @media
.btn {
padding: 1rem 2rem;
@media (max-width: 600px) {
& {
padding: 0.75rem 1.5rem;
}
}
}Note
π¨ Styling Nested Child Selectors Inside Media Queries
Nested children + media queries
.card {
padding: 1rem;
h2 {
font-size: 1.5rem;
}
@media (max-width: 500px) {
h2 {
font-size: 1.2rem;
}
}
}Child selectors remain accessible inside the nested media query.
π§ͺ Real-World Examples
1οΈβ£ Responsive Navigation Menu
Navbar Example
nav {
display: flex;
gap: 1rem;
@media (max-width: 700px) {
flex-direction: column;
gap: 0.5rem;
}
}2οΈβ£ Responsive Grid Component
Grid Example
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
@media (max-width: 800px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 500px) {
grid-template-columns: 1fr;
}
}3οΈβ£ Button With Touch-Friendly Size
Touch UI Example
.btn {
padding: 0.75rem 1.5rem;
@media (pointer: coarse) {
padding: 1rem 2rem;
}
}Great for mobile devices or touch screens.
β οΈ Nesting Rules & Gotchas
- β @media must be inside a selector β not at the root of nesting
- β Cannot nest other at-rules that don't support being nested
- β Deep nesting (selectors + media) can become hard to read
Note
π₯ Summary
Nested @media rules allow you to write responsive styles directly inside the component they belong to. This makes CSS cleaner, more modular, and easier to maintain β especially in component-driven systems or large applications.
Learn more βMDN @media Docs π