CSS Nesting

One of our favorite CSS preprocessor features is now built into the language: nesting style rules.

Before nesting, every selector needed to be explicitly declared, separately from one another. This leads to repetition, stylesheet bulk and a scattered authoring experience.

Before
.nesting {
  color: hotpink;
}

.nesting > .is {
  color: rebeccapurple;
}

.nesting > .is > .awesome {
  color: deeppink;
}

After nesting, selectors can be continued and related style rules to it can be grouped within.

After
.nesting {
  color: hotpink;

  > .is {
    color: rebeccapurple;

    > .awesome {
      color: deeppink;
    }
  }
}

Try this in browser.

Nesting helps developers by reducing the need to repeat selectors while also co-locating style rules for related elements. It can also help styles match the HTML they target. If the .nesting component in the previous example was removed from the project, you could delete the entire group instead of searching files for related selector instances.

Nesting can help with: - Organization - Reducing file size - Refactoring

Nesting is available from Chrome 112 and also available to try in Safari Technical Preview 162.

Getting started with CSS Nesting

Throughout the rest of this post,the following demo sandbox is used to help you visualize the selections. In this default state, nothing is selected and everything is visible. By selecting the various shapes and sizes, you can practice the syntax and see it in action.