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.

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

  &:hover {
    background: #f3f4f6;
  }

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

Nesting Media Queries and Modifiers

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

.button {
  padding: 8px 16px;

  &.primary {
    background: blue;
  }

  @media (min-width: 768px) {
    padding: 12px 24px;
  }
}

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

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation