Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Variables, Nesting and Partials

Sass Nesting and the Parent Selector (&)

Write cleaner CSS with Sass nesting: nested selectors and combinators, the & parent selector, nested properties and media queries, @at-root and depth limits.

HTML is a tree: a navigation bar contains a list, the list contains items, the items contain links. Plain CSS makes you repeat nav ul li a every time you style one of those pieces. Nesting lets you write the rules the same way the markup is shaped, and Sass flattens them into normal selectors when it compiles. (Modern CSS now has native nesting too, but Sass nesting works everywhere and has extra tricks.)

Basic nesting

Put a rule inside another rule and Sass joins the selectors with a descendant combinator (a space):

SCSS
nav {
  background: #0f172a;

  ul { list-style: none; margin: 0; }
  li { display: inline-block; }
  a  { color: white; text-decoration: none; }
}

That compiles to nav { ... }, nav ul { ... }, nav li { ... } and nav a { ... }. You can also nest selectors that contain combinators, with the combinator at the start of the nested rule:

SCSS
.menu {
  > li { margin: 0; }       // .menu > li
  + .menu { margin-top: 8px; }   // .menu + .menu
  ~ p { color: gray; }      // .menu ~ p
}

A selector list nests as a group, so .a, .b { .c { } } becomes .a .c, .b .c.

flowchart TD
  N["nav"] --> UL["ul"]
  UL --> LI["li"]
  LI --> A["a"]
  A -.->|"compiles to"| S["nav ul li a"]

The nesting in your SCSS mirrors the structure of the HTML, but the CSS output is a flat list of selectors.

The parent selector: &

Inside a nested rule, & stands for the complete parent selector. It is what lets you attach pseudo-classes, modifiers and context to the same element rather than a descendant:

SCSS
.button {
  background: #0ea5e9;

  &:hover { background: #0284c7; }    // .button:hover
  &:focus-visible { outline: 3px solid; }
  &.is-active { font-weight: 700; }   // .button.is-active
  &[disabled] { opacity: .5; }        // .button[disabled]
}

Without the &, :hover would create a descendant selector (.button :hover), which is almost never what you meant.

Suffixes: &-name and &__name

You can append text to the parent with &. This is how people write BEM (Block Element Modifier) names without repeating the block:

SCSS
.card {
  padding: 1rem;

  &__title { font-weight: 700; }   // .card__title
  &__body  { color: #475569; }     // .card__body
  &--featured { border: 2px solid gold; }   // .card--featured
}

The suffix feature only works when & is at the start of the compound selector. It is covered in more depth in BEM and component patterns.

Context: placing & after something

Put the & at the end to apply a style to the element when it is inside some other context:

SCSS
.logo {
  color: black;

  .dark-mode & { color: white; }   // .dark-mode .logo
  body.rtl & { float: right; }     // body.rtl .logo
}
Nesting and the parent selector

Nested properties

CSS properties often share a prefix: font-family, font-size, font-weight. Sass lets you nest them inside a block named after the prefix. Write the prefix, a colon, then braces:

SCSS
.title {
  font: {
    family: Georgia, serif;
    size: 2rem;
    weight: 700;
  }
  border: 1px solid {
    left: 6px solid #0ea5e9;
  }
}

The result is font-family, font-size, font-weight and a border followed by border-left. Some teams love this and others never use it, since the flat form is just as clear.

Nested media queries

You can place @media (and @supports) inside a rule. Sass bubbles it up and wraps the parent selector for you, which keeps responsive behavior next to the styles it changes:

SCSS
.sidebar {
  width: 100%;

  @media (min-width: 768px) {
    width: 280px;
  }
}

The output is .sidebar { width: 100%; } followed by @media (min-width: 768px) { .sidebar { width: 280px; } }. Media queries can nest inside each other, and Sass joins their conditions with and.

Nested properties and media queries

@at-root: escaping the nest

Sometimes you want to write a rule inside a parent for organization but have it compile without the parent selector. @at-root does that:

SCSS
.card {
  color: black;

  @at-root .card-list {   // compiles to .card-list, not .card .card-list
    display: grid;
  }
}

It is mostly useful in mixins and with interpolation, where you build selectors programmatically.

Declarations after nested rules

CSS applies rules in the order you write them. Current Dart Sass follows the native CSS nesting behavior: a plain declaration written after a nested rule is emitted in a second rule for the same selector, placed after the nested one, so the order you wrote is the order the cascade sees:

SCSS
.box {
  color: red;
  &:hover { color: blue; }
  margin: 0;          // after the nested rule
}

This compiles to .box { color: red; }, then .box:hover { color: blue; }, then .box { margin: 0; }. Older Sass versions moved margin up into the first rule, and some of them print a "mixed declarations" deprecation warning for code like this. To stay compatible everywhere, keep declarations first, or wrap late ones in & { ... }.

Don't nest too deeply

Because nesting is so easy, it is easy to overdo. Every level adds specificity and makes selectors long and brittle:

SCSS
// Hard to override, tied to the exact markup
.page { .main { .content { .article { h2 { a { color: red; } } } } } }

Rules of thumb used by many teams:

  • Aim for three levels or fewer.
  • Don't nest just because the HTML does. Give components their own class names.
  • Never nest only to avoid typing a class name once.
  • Check the compiled CSS: if a selector is longer than you would write by hand, flatten it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does .button { &:hover { } } compile to?

    & is replaced by the parent selector with no space, so the pseudo-class attaches to the same element.
  2. 2. What does .card { &__title { } } compile to?

    & can be followed by a suffix, which Sass appends directly to the parent selector. This is how BEM names are written.
  3. 3. How do you style .logo only inside .dark-mode?

    Placing & after the context selector produces .dark-mode .logo.
  4. 4. What does @at-root do?

    @at-root emits the nested rule at the stylesheet root, so the parent selector is not prepended.

Summary

  • Nested rules compile to descendant selectors; combinators can start a nested rule.
  • & is the parent selector: use it for pseudo-classes (&:hover), modifiers (&.active), suffixes (&__title) and context (.dark &).
  • Nested properties (font: { ... }) and nested @media keep related styles together.
  • @at-root emits a rule without its parent.
  • Keep nesting to roughly three levels and put declarations before nested rules.

Next: Partials and @use