Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 139 ยท Modern CSS

CSS Nesting

Learn native CSS nesting, how the & selector works, how to nest media and container queries, and how nested rules affect specificity compared with Sass.

For years, writing CSS for a component meant repeating its name over and over: .card, .card h2, .card p, .card a:hover. Preprocessors such as Sass became popular partly because they let you nest those rules inside one block. Today you don't need a build step for that. Every modern browser understands nesting natively.

In this lesson you will learn how nested rules are written, what the & selector means, how to nest media queries right next to the styles they change, and the few places where native nesting behaves differently from Sass.

Your first nested rule

A nested rule is simply a style rule written inside another style rule. The inner selector is relative to the outer one:

CSS
.card {
  padding: 1rem;
  border: 1px solid #ccc;

  h2 {
    margin-top: 0;
  }

  p {
    color: #555;
  }
}

The browser reads this exactly as if you had written:

CSS
.card { padding: 1rem; border: 1px solid #ccc; }
.card h2 { margin-top: 0; }
.card p { color: #555; }

The nested h2 means "an h2 that is a descendant of .card". Everything that belongs to the card now lives in one block, so it is easy to find, move or delete.

A nested card

Change the p rule inside .card and notice that the last paragraph never changes. Nested selectors are always scoped to the parent selector.

The & nesting selector

The ampersand & stands for the parent selector. You need it whenever the inner selector should attach to the parent itself rather than to a descendant. The classic examples are pseudo-classes and extra classes:

CSS
.button {
  background: royalblue;

  &:hover {
    background: navy;        /* .button:hover */
  }

  &.is-danger {
    background: crimson;     /* .button.is-danger */
  }

  .icon {
    margin-right: 0.25rem;   /* .button .icon */
  }
}

Notice the difference between &:hover and :hover. Without the &, a nested :hover would mean "any hovered descendant of .button", which is rarely what you want. With the &, it means "the button itself, when hovered".

You can also put & at the end of a selector to style the parent in a particular context:

CSS
.button {
  color: white;

  .toolbar & {
    font-size: 0.875rem;     /* .toolbar .button */
  }
}

That reads naturally: "a button inside a toolbar". It keeps context-specific tweaks next to the component they affect.

Using & for states and variants

Hover over the buttons and press Tab to see the focus ring. The two buttons in the toolbar are smaller because of the .toolbar & rule.

Nesting media and container queries

This is where nesting really shines. You can put an at-rule such as @media, @container or @supports directly inside a style rule. The declarations inside apply to the parent selector, but only when the condition is true:

CSS
.gallery {
  display: grid;
  gap: 1rem;
  grid-template-columns: 1fr;

  @media (width >= 40rem) {
    grid-template-columns: repeat(3, 1fr);
  }
}

Instead of hunting through a separate media query block at the bottom of the file, every breakpoint for the gallery sits right next to its base styles. The width >= 40rem range syntax is covered in Media Queries.

A nested media query

Resize the preview pane (or your window). Below about 480px wide the three boxes stack; above it they sit in a row. Notice the rules nested two levels deep, div inside .stats and strong inside div, which compile to .stats div strong.

Specificity of nested rules

A nested selector gets the specificity of the parent plus its own. .card { h2 { } } behaves like .card h2, which is (0,1,1). You can learn how those numbers work in Specificity.

There is one subtle detail. When the parent is a list of selectors, the & behaves like :is() wrapped around that list. :is() takes the specificity of its most specific argument:

CSS
#sidebar, .panel {
  a { color: teal; }
}

/* Behaves like :is(#sidebar, .panel) a
   so BOTH matches get ID-level specificity (1,0,1) */

A link inside .panel ends up with ID-level specificity, even though .panel contains no ID. Keep selector lists in a parent rule at similar specificity, or avoid IDs in them altogether, and this never bites.

How native nesting differs from Sass

If you already know Sass, most of your habits transfer. A few things do not:

  • No string concatenation. In Sass, &__title inside .card produces .card__title. Native CSS treats & as a real selector, not text, so &__title is invalid. Write .card__title out in full instead. That matters for BEM naming.
  • & is like :is(). As shown above, it can raise specificity in ways Sass output would not.
  • No build step. The browser keeps the nested structure in its style sheets, and DevTools shows it nested too.

Support: native nesting has worked in all major browsers since 2023. The very first versions required nested selectors to start with a symbol (so you had to write & h2 instead of h2). That restriction was dropped shortly afterward and every current browser accepts a bare h2. If you must support browsers from early 2023, writing & h2 works everywhere.

Keep declarations first

Write a rule's own declarations before its nested rules. The browser does handle declarations written after a nested block, but code that mixes them is hard to read, and older engines grouped all of a rule's declarations together regardless of where they appeared.

CSS
/* Clear: declarations, then nested rules */
.alert {
  padding: 1rem;
  border-left: 4px solid orange;

  p { margin: 0; }
}

How deep should you nest?

Nesting is pleasant to write, and that makes it easy to overdo. Deeply nested code produces long, highly specific selectors that are hard to override later:

CSS
/* Too deep: .page .main .article .content ul li a */
.page {
  .main {
    .article {
      .content {
        ul { li { a { color: red; } } }
      }
    }
  }
}

A good rule of thumb is no more than two or three levels. Nest states (&:hover), variants (&.is-active), media queries and direct parts of a component. Avoid nesting just to mirror your HTML structure. If the HTML changes, every level of nesting becomes a reason for the CSS to break.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Inside .menu { ... }, which nested rule styles the menu itself when it is hovered?

    & stands for the parent selector, so &:hover becomes .menu:hover. A bare :hover would target hovered descendants instead.
  2. 2. What does .toolbar & { } produce when nested inside .btn?

    The & is replaced by the parent selector wherever it appears, so this targets a .btn that is a descendant of .toolbar.
  3. 3. In native CSS, what happens to &__title { } nested inside .card?

    Native nesting does not concatenate strings. Write .card__title as its own selector instead.
  4. 4. Why can nesting under #nav, .footer { a { } } give a surprising result?

    :is() takes the specificity of its most specific argument, so links in .footer get the same high specificity as links in #nav.

Summary

  • Native CSS nesting lets you write rules inside rules, with no preprocessor.
  • & is the parent selector. Use it for states (&:hover), extra classes (&.active) and contexts (.dark &).
  • @media, @container and @supports can be nested inside a rule to keep breakpoints next to the styles they change.
  • Nested selectors behave like :is(), so a parent selector list takes the highest specificity in the list.
  • Native & cannot build new class names like Sass's &__title.
  • Keep nesting shallow: two or three levels is plenty.

Next: Feature Queries (@supports), where you will learn to use new CSS safely by checking whether the browser understands it first.