sass The parent selector (&)


Example

Nesting is great for keeping related selectors together to make it easier for future developers to understand your code. The parent selector, represented by an ampersand ("&") can help do that in more complex situations. There are several ways its can be used.

Create a new selector that requires both the parent selector and another on the same element by placing the new selector directly after a parent selector.

// SCSS
.parent {

  &.skin {
    background: pink;
  }
}
// CSS output
.parent.skin {
  background: pink;
}

Have the parent appear after a nested selector in the compiled CSS by placing the parent selector after the nested selector.

// SCSS
.parent {

  .wrapper & {
    border: 1px solid black;
  }
}
// CSS output
.wrapper .parent {
  border: 1px solid black;
}

States and pseudo-elements

Besides using nesting for classes and children, nesting with the parent selector is also commonly used to combine the states of :active, :hover and :focus for links.

// SCSS
a {
  color: blue;

  &:active,
  &:focus {
    color: red;
  }

  &:visited {
    color: purple;
  }
}
// CSS output
a {
  color: blue;
}

a:active,
a:focus {
  color: red;
}

a:visited {
  color: purple;
}

Similarly, you can style pseudo-elements by nesting with the parent selector.

// SCSS
.parent {

  &::after {
    display: table;
    clear: both;
    content: '';
  }

  &::only-child {
    font-weight: bold;
  }
}
// CSS output
.parent::after {
  display: table;
  clear: both;
  content: '';
}

.parent::only-child {
  font-weight: bold;
}