What is CSS Nesting?
CSS nesting is a native browser feature that allows style rules to be written inside other style rules, following the hierarchical structure of your HTML. This approach, long available in preprocessors like Sass, is now built directly into CSS--eliminating build step dependencies while improving code organization and maintainability.
Unlike preprocessor nesting, native CSS nesting uses the & selector explicitly or implicitly, and selectors are not treated as strings. This means patterns like &--modifier that work in SCSS don't concatenate automatically in native CSS. Understanding this fundamental difference is essential for developers migrating from preprocessors or adopting native nesting for new projects.
Throughout this guide, you'll learn the complete syntax for nesting selectors, at-rules like @media and @supports, and discover practical patterns that will transform how you write component styles. Whether you're building a custom website or a complex web application using modern AI integration, native CSS nesting helps keep related styles together where they belong. For visual transformations beyond basic nesting, explore our guide on CSS transforms to add sophisticated animations and effects to your nested components.
Browser Support
112+
Chrome/Edge
117+
Firefox
17.2+
Safari
Basic Nesting Syntax
The nesting selector (&) explicitly references the parent selector in nested rules. This explicit approach ensures clear selector composition and prevents ambiguity in your stylesheets. Both explicit and implicit nesting are valid, but each has specific use cases.
Explicit nesting with & allows you to combine the parent selector with any valid CSS selector. The & is replaced with the entire parent selector chain, creating a compound selector.
Implicit nesting (without &) automatically inserts a descendant combinator (space) between the parent and child selectors. This works well for simple descendant relationships but requires explicit & when you need compound selectors or combinators.
For simple descendant relationships, implicit nesting keeps code concise. For pseudo-classes, modifiers, and combinators, explicit & ensures the selector behaves exactly as intended. This is especially important when building components for enterprise web applications where selector specificity matters. To learn more about modern CSS techniques, see our guide on CSS Containment for performance optimization.
1/* Explicit nesting with & */2.parent {3 color: blue;4 & .child {5 color: red;6 }7}8 9/* Implicit nesting (browser adds space) */10.parent {11 color: blue;12 .child {13 color: red;14 }15}16 17/* Both produce: .parent .child { color: red; } */Compound Selectors and the & Requirement
Compound selectors--selectors targeting elements with multiple conditions--require the explicit & selector. Without it, browsers insert a space, fundamentally changing the selector's meaning from "same element with both classes" to "descendant element with this class."
The difference is significant: .card .featured matches any element with class featured that is a descendant of a .card, while .card&.featured matches only elements that have both card and featured classes simultaneously. This distinction is crucial for BEM-style modifier patterns where you need to apply styles conditionally based on multiple classes.
The explicit & requirement exists because native CSS treats selectors differently than preprocessor string concatenation. Understanding this behavior prevents common bugs when migrating from SCSS or Less. For teams implementing SEO-friendly web development, clean CSS architecture contributes to faster page loads and better crawlability.
1/* WRONG: Creates descendant selector */2.card {3 .featured {4 /* Becomes: .card .featured */5 }6}7 8/* CORRECT: Creates compound selector */9.card {10 &.featured {11 /* Becomes: .card.featured */12 }13}14 15/* Multiple classes on same element */16.button {17 &.primary.large {18 /* Becomes: .button.primary.large */19 }20}Using Combinators with Nesting
CSS combinators--child (>), next-sibling (+), and subsequent-sibling (~)--work seamlessly with nesting when you use the explicit & selector. The child combinator targets direct descendants, while sibling combinators target elements that follow other elements in the DOM.
The child combinator is particularly useful for component styling where you want to target only immediate children rather than all descendants. Next-sibling combinators work well for styling elements that immediately follow others, such as paragraphs after headings or form labels before inputs. The subsequent-sibling combinator targets all matching siblings that follow, useful for styling all alerts after the first or spacing between list items.
These combinator patterns become especially powerful when combined with responsive design techniques using nested @media queries, creating component styles that are self-contained and easy to maintain. When building modern web applications, keeping these relationships organized within nested rules significantly improves developer experience. Related techniques include CSS Easing Functions for smooth animations and CSS Motion Path for complex animations.
1/* Child combinator */2.container {3 & > .item {4 /* Direct children only */5 }6}7 8/* Next-sibling combinator */9h2 {10 color: #333;11 & + p {12 /* First paragraph after h2 */13 margin-top: 1rem;14 }15}16 17/* Subsequent-sibling combinator */18.alert {19 & ~ .alert {20 /* Additional alerts after the first */21 margin-top: 0.5rem;22 }23}Nesting At-Rules
One of CSS nesting's most powerful features is the ability to nest at-rules like @media, @supports, @layer, and @container directly within style rules. This keeps related responsive and conditional styles together, eliminating the selector repetition that plague traditional CSS organization.
Nested at-rules follow the same structure as their non-nested equivalents but are scoped to their parent selector. MDN's documentation on nested at-rules demonstrates how @media, @supports, and @layer rules can be placed directly inside style rules, creating a more intuitive structure that mirrors component-based development patterns.
This approach is particularly valuable for responsive component design, where responsive styles belong with the component they affect rather than in separate sections of the stylesheet. It also simplifies refactoring since changes to the parent selector automatically apply to all nested at-rules. For performance-focused development, combining CSS nesting with CSS Containment helps browsers render pages more efficiently. To understand how CSS data types work within nested rules and at-rules, see our detailed guide on CSS data types.
1/* Nested @media */2.card {3 font-size: 1rem;4 5 @media (min-width: 768px) {6 font-size: 1.25rem;7 display: grid;8 grid-template-columns: 1fr 1fr;9 }10 11 @media (min-width: 1024px) {12 grid-template-columns: 1fr 1fr;13 }14}1/* Nested @supports */2.element {3 display: flex;4 5 @supports (display: grid) {6 display: grid;7 gap: 1rem;8 }9}10 11/* Nested @layer */12.styles {13 @layer base {14 color: #333;15 16 @layer components {17 .button {18 padding: 0.5rem 1rem;19 }20 }21 }22}Performance and Best Practices
While CSS nesting offers significant maintainability benefits, understanding its performance implications and following established best practices ensures optimal results in production environments.
Limit Nesting Depth
Excessive nesting creates overly specific selectors that are difficult to maintain and can impact rendering performance. Most experts and Chrome's developer guidance recommend limiting nesting to 2-3 levels maximum. Beyond this depth, selectors become difficult to reason about and may override styles unexpectedly.
When to Avoid Nesting
- Component boundaries: Keep components flat and compose them in HTML structure rather than deep nesting
- Utility patterns: Tailwind-style utility classes work better without nesting for atomic styling
- Global styles: Reserve nesting for component-local styles where the relationship is meaningful
File Size Considerations
Modern build tools can optimize nested CSS output, but the primary benefit of nesting is maintainability rather than file size reduction. The real performance gain comes from better-organized code that is easier to debug and maintain, reducing the likelihood of CSS bloat over time. Pair this with CSS Scoping for component-level style isolation.
Following these best practices helps teams adopt CSS nesting gradually, starting with new components and expanding to existing codebases during refactoring efforts.
1/* AVOID: Excessive nesting */2.component {3 & .inner {4 & .content {5 & .item {6 & .link {7 color: blue; /* Too deep! */8 }9 }10 }11 }12}13 14/* BETTER: Flat structure with BEM */15.component__inner__content__item__link {16 /* Still specific, but more predictable */17}18 19/* BETTER YET: Shallow nesting */20.component {21 &__inner {22 /* Level 1 */23 &__content {24 /* Level 2 - Consider stopping here */25 }26 }27}1/* WRONG: String concatenation doesn't work */2.card {3 &--header {4 /* INVALID: Produces ".card --header" */5 }6}7 8/* CORRECT: BEM modifier patterns */9.card {10 /* Block */11 &--featured {12 /* Becomes: .card--featured */13 border-color: blue;14 }15}16 17/* OR: Using nested class */18.card {19 &.card--featured {20 /* Explicit compound selector */21 border-color: blue;22 }23}Practical Example: Card Component
Putting it all together, here's how a complete card component might look using CSS nesting with proper organization, variants, and responsive behavior. This example demonstrates the patterns discussed throughout this guide in a realistic component structure.
The card uses BEM-style naming with nested selectors for its internal structure (header, body, footer), modifier classes for variants (featured, elevated), pseudo-classes for states (hover, focus-within), and nested media queries for responsive design. Each section is clearly delineated, making the component easy to understand and modify.
This pattern is particularly effective for front-end development projects where component-based architecture is essential for maintainability at scale. When combined with CSS Value Functions for dynamic calculations and CSS Text for typography control, you can build sophisticated component systems.
For teams implementing AI-powered web applications, well-structured CSS using nesting improves collaboration between developers and reduces maintenance overhead.
1.card {2 display: flex;3 flex-direction: column;4 border: 1px solid #e2e8f0;5 border-radius: 0.5rem;6 overflow: hidden;7 background: white;8 9 /* Card Header */10 &__header {11 padding: 1rem;12 border-bottom: 1px solid #e2e8f0;13 background: #f8fafc;14 }15 16 /* Card Body */17 &__body {18 padding: 1rem;19 flex: 1;20 }21 22 /* Card Footer */23 &__footer {24 padding: 1rem;25 border-top: 1px solid #e2e8f0;26 background: #f8fafc;27 display: flex;28 justify-content: flex-end;29 gap: 0.5rem;30 }31 32 /* Variants */33 &--featured {34 border-color: #3b82f6;35 box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.1);36 37 & .card__header {38 background: #eff6ff;39 color: #1e40af;40 }41 }42 43 &--elevated {44 box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);45 }46 47 /* States */48 &:hover {49 border-color: #94a3b8;50 }51 52 &:focus-within {53 outline: 2px solid #3b82f6;54 outline-offset: 2px;55 }56 57 /* Responsive */58 @media (min-width: 768px) {59 flex-direction: row;60 61 &__header,62 &__body,63 &__footer {64 padding: 1.5rem;65 }66 }67}Frequently Asked Questions
Is CSS nesting supported in all modern browsers?
Yes, CSS nesting is supported in Chrome 112+, Firefox 117+, Safari 17.2+, and Edge 112+. All major modern browsers now support this feature natively. For projects requiring support for older browsers, use @supports queries to provide fallbacks.
Can I use CSS nesting with Tailwind CSS?
Yes, CSS nesting works alongside Tailwind CSS seamlessly. Use nesting for custom component styles while using Tailwind's utility classes for atomic styling. This hybrid approach combines the best of both worlds.
How is CSS nesting different from SCSS nesting?
The main difference is that native CSS nesting doesn't treat selectors as strings, so `&--modifier` doesn't concatenate like in SCSS. Native CSS also requires explicit `&` for compound selectors and doesn't support SCSS-style parent selectors in all contexts.
Should I migrate existing SCSS to native CSS nesting?
Consider migration for new features or during refactoring. Benefits include smaller build outputs (no preprocessor needed) and native browser parsing. However, evaluate the complexity of fixing patterns like string concatenation that behave differently in native CSS.
Conclusion
CSS nesting brings the organizational benefits of preprocessor nesting directly to native CSS, eliminating build step dependencies while improving stylesheet maintainability. By keeping related styles together and reducing selector repetition, nested CSS creates more readable and maintainable codebases.
Key takeaways:
- Use the
&selector explicitly for compound selectors, pseudo-classes, and combinators - Limit nesting depth to 2-3 levels for maintainable, performant stylesheets
- Nest at-rules like
@mediato keep responsive styles with their components - Remember that native CSS nesting doesn't support string concatenation like SCSS
- Browser support is excellent across all modern browsers
Adoption strategy: Start by using native CSS nesting in new components and projects. For existing codebases, gradually introduce nesting during refactoring efforts. The explicit nature of native CSS nesting actually encourages better selector practices compared to preprocessor nesting.
Ready to modernize your stylesheet architecture? Our team specializes in building performant, maintainable web applications using modern CSS techniques. Contact us to discuss how we can help you adopt modern CSS practices in your projects. For advanced selector patterns, see our guide on CSS conditional rules. To explore shape-based styling with nesting, see our Basic Shape guide, and for typographic control see Font Variant Position.
Sources
-
MDN Web Docs: Using CSS Nesting - Comprehensive official documentation covering CSS nesting syntax, examples, and best practices
-
Chrome for Developers: CSS Nesting - Browser vendor documentation with practical examples and browser support information
-
MDN Web Docs: CSS Nesting At-Rules - Reference for nesting at-rules in CSS including @media, @supports, and @layer