CSS Nested Selectors (&)

Definition and Usage

CSS Nesting (&) Selectors are used to apply styles to elements in the context of another element.

Nesting reduces the need to repeat selectors for related elements.

Example

Example 1

Before nesting, you must explicitly declare each selector separately, as shown below:

.box {
  border: 2px solid green;
  background-color: beige;
  font-family: monospace;
  font-size: 20px;
}
.box > a {
  color: green;
}
.box > a:hover {
  color: white;
  background-color: salmon;
}

Try it yourself

Example 2

After nesting, the selector is extended, and the related style rules are grouped within the parent rule:

.box {
  border: 2px solid green;
  background-color: beige;
  font-family: monospace;
  font-size: 20px;
  & > a {
    color: green;
    &:hover {
      color: white;
      background-color: salmon;
    }
  }
}

Try it yourself

Tip:If the .box style in the previous example should be removed from your project, you can remove the entire group without searching for related selectors.

CSS Grammar

parentrule {
  css declarations;
  & childrule {
    css declarations;  } 
}

Technical Details

Version: CSS Nesting Module

Browser Support

Chrome Edge Firefox Safari Opera
120 120 117 17.2 106