Codectionary / Developer documentation / CSS

Native CSS Nesting

Native CSS nesting lets you write selectors inside other selectors, similar to what Sass offered for years, but now supported directly in browsers with no build step required. The & symbol explicitly references the parent selector, useful for pseudo-classes, modifiers, and compound selectors.

Syntax

.parent {
  & .child { }
  &:hover { }
}

Examples

Basic Nesting

Nesting descendant selectors and pseudo-classes inside a parent rule.

/* Demo setup: sizing, structure or neutral surfaces. */
.card{border:1px solid #94a3b8;color:#172b4d}

.card {
  padding: 1rem;
  background: white;

  &:hover {
    background: #f3f4f6;
  }

  & .title {
    font-size: 1.25rem;
    font-weight: bold;
  }
}
  1. The title is inside the card, so the nested descendant selector matches it.
  2. Hovering the card activates its nested state rule.
  3. Native nesting is parsed by the browser; it is not a Sass compilation step.
HTML used by this example
<article class="card"><h3 class="title">Nested selectors</h3><p>Hover this article to reveal the nested hover state.</p></article>

Nesting Media Queries and Modifiers

Keeping related responsive and state styles physically close to the base rule.

/* Demo setup: sizing, structure or neutral surfaces. */
button{border:1px solid #64748b;border-radius:.25rem}.primary{color:white}

.button {
  padding: 8px 16px;

  &.primary {
    background: blue;
  }

  @media (min-width: 768px) {
    padding: 12px 24px;
  }
}
  1. The primary button matches the nested modifier through its second class.
  2. The nested media query changes padding when the iframe becomes wide enough.
  3. Compare the two buttons and resize the preview rather than expecting a media-query effect at every width.
HTML used by this example
<button class="button primary">Primary action</button> <button class="button">Ordinary action</button>

Parameters and values

  • & (nesting selector): Explicitly references the parent selector within a nested rule

Best practices

  • Use native nesting to keep a component's related styles - base, hover states, modifiers, responsive rules - physically grouped together
  • Use & explicitly when nesting a compound selector (&.active) or pseudo-class (&:hover), since omitting it changes the meaning to a descendant selector instead
  • Avoid nesting too many levels deep - beyond 2-3 levels, generated specificity and selector length both grow, hurting maintainability
  • This is now broadly supported without a preprocessor, but check your specific browser support target if you need to support noticeably older browsers

Browser compatibility

chrome
Yes
firefox
Yes
safari
Yes
edge
Yes

These are the existing reference’s support labels, not tested minimum versions. Individual values and APIs can have different support. Check the linked specification before choosing a browser target.

CSS specifications (modules)

Specifications & further reading