Nesting

Write Related Rules Inside Their Parent

Nesting

Native CSS nesting lets you write related selectors inside a parent rule — like Sass / Less, but built in.

3 min read Level 1/5 #css#nesting#modern-css
What you'll learn
  • Write nested rules
  • Use `&` for self-reference
  • Avoid over-nesting

Native CSS nesting lets you write related selectors inside a parent rule. No preprocessor needed.

Before vs After

/* Old way */
.card { padding: 1rem; }
.card h2 { margin-top: 0; }
.card.featured { background: gold; }
.card:hover { transform: translateY(-2px); }
/* With nesting */
.card {
  padding: 1rem;

  & h2 {
    margin-top: 0;
  }

  &.featured {
    background: gold;
  }

  &:hover {
    transform: translateY(-2px);
  }
}

& is the parent selector. Required when you want to reference the parent (e.g., &:hover, &.featured).

When & Is Optional

If a nested selector starts with a combinator, you can skip &:

.card {
  > h2 { ... }     /* direct child */
  + .card { ... }  /* sibling */
}

Don’t Over-Nest

Deep nesting bloats specificity:

/* ✗ Three levels deep — high specificity */
.layout {
  .card {
    .header {
      .title { ... }
    }
  }
}

A flat selector or a focused class beats this. Two levels of nesting is a reasonable ceiling.

Media Queries Inside Nesting

A great use of nesting — keep responsive rules with their component:

.layout {
  display: block;

  @media (min-width: 768px) {
    display: grid;
    grid-template-columns: 250px 1fr;
  }
}

The media query rule is part of the component’s definition.

Container Queries Too

.card {
  display: block;

  @container (min-width: 500px) {
    display: grid;
    grid-template-columns: 200px 1fr;
  }
}

Up Next

Cascade layers — organize rules by priority.

Cascade Layers →