Native CSS Nesting Explained

What Native CSS Nesting Is

Native nesting lets a selector be written inside another selector's block, so a component's related rules can be grouped together visually - a pattern long available only through preprocessors like Sass, now built directly into CSS itself.

A Basic Example

.card {
  padding: 16px;
  border: 1px solid #ddd;

  & .card-title {
    font-size: 1.25rem;
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

The & symbol refers back to the parent selector - .card in this case - the same way it does in Sass, letting pseudo-classes and descendant rules live directly inside the component's own block.

Nesting Media Queries Too

.card {
  width: 100%;

  @media (min-width: 768px) {
    width: 50%;
  }
}

A media query can now be nested directly inside the rule it affects, instead of being written far away in a separate block - keeping a component's responsive behavior next to its base styles.

Why This Matters

  • Related styles for one component stay visually grouped, improving readability in larger stylesheets.
  • Projects that previously needed Sass purely for nesting may no longer need a build step for that reason alone.
  • The & reference works the same way developers coming from Sass or Less already expect.

A Caution on Overusing Nesting

Just like in Sass, nesting selectors many levels deep increases specificity and can make styles harder to override later. Keeping nesting shallow - typically no more than two or three levels - keeps the benefit of readability without the downside of overly specific, hard-to-override rules.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.