← Lessons

quiz vs the machine

Gold1360

Frontend

The CSS Nesting

Write nested rules natively without a preprocessor and understand how the ampersand resolves selectors.

4 min read · core · beat Gold to climb

Nesting rules natively

Native CSS nesting lets you place rules inside other rules, so styles for a component and its parts live together. A nested selector is read relative to its parent rule, which cuts repetition and keeps related styles close.

  • A nested rule targets descendants of the parent selector.
  • The ampersand stands in for the parent selector explicitly.
  • Nesting works for normal selectors and at rules like media.

Using the ampersand

The ampersand makes the parent reference explicit, which matters for compound selectors and pseudo classes. Without it, a nested type or class selector implies a descendant, while the ampersand attaches directly to the parent.

  • An ampersand followed by hover styles the parent on hover.
  • Combining the ampersand with a class makes a compound selector.
  • Media queries can nest so responsive tweaks stay beside the base rule.

Native nesting does not flatten at build time, so the browser resolves it live, which keeps specificity rules clear and predictable.

Key idea

CSS nesting places related rules inside a parent and uses the ampersand to reference that parent, reducing repetition while the browser resolves selectors live.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the ampersand represent in a nested CSS rule?

2. How does a bare nested class selector behave without an ampersand?