Nesting Rules

Nest selectors to mirror your HTML structure.

Syntaxparent { child { property: value; } }

Nesting lets you place selectors inside other selectors, matching the way your HTML is nested. Sass expands the nesting into flat descendant selectors when it compiles.

Nested Sass rules expand into flat CSS descendant selectorsnav {ul {li { ... }}}nested SCSSnav ul {nav ul li {flat CSS
Each level of nesting becomes a space-separated descendant selector.

Nesting keeps related rules together and reduces repetition, but nest sparingly — deeply nested selectors produce long, over-specific CSS.

Example

Example · css
nav {
  background: #333;

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li {
    display: inline-block;
  }
}

/* Compiles to:
nav { background: #333; }
nav ul { margin: 0; padding: 0; list-style: none; }
nav li { display: inline-block; }
*/

When to use it

  • A developer nests all .card child element rules inside .card to visually group related styles and avoid repeating the parent selector prefix.
  • A team mirrors their BEM HTML structure in Sass nesting so anyone reading the stylesheet can instantly identify which styles belong to which component.
  • A developer nests media queries inside the selector they affect, keeping the responsive rules co-located with the component rather than in a separate block.

More examples

Basic child selector nesting

Groups all card sub-element styles under .card so the Sass structure mirrors the HTML hierarchy.

Example · css
.card {
  padding: 1rem;
  border: 1px solid #e5e7eb;

  header {
    font-size: 1.25rem;
    font-weight: 600;
  }

  p {
    color: #6b7280;
    line-height: 1.6;
  }
}

Nested media query

Places the responsive breakpoint rule directly inside its component selector, keeping layout changes co-located with base styles.

Example · css
.sidebar {
  width: 100%;

  @media (min-width: 768px) {
    width: 260px;
    flex-shrink: 0;
  }
}

Multi-level nesting for navigation

Nests li inside .nav and a inside li, compiling to .nav li and .nav li a without repeating the ancestor selectors.

Example · css
.nav {
  display: flex;
  gap: 1rem;

  li {
    list-style: none;

    a {
      color: #111;
      text-decoration: none;
    }
  }
}

Discussion

  • Be the first to comment on this lesson.