UX Design and Development course

Parent selector reference

It is useful to use a nested rule’s parent selector in other ways than the default. For instance, you might want to have special styles for when that selector is hovered over. In these cases, you can explicitly specify where the parent selector should be inserted using the & character.

Pseudo classes

This technique will work for any pseudo class such as :after, :before, :active, and so on.

SCSS

a {
  color: red;
  text-decoration: none;
  &:hover {
    text-decoration: underline;
  }
}

Sass

a
  color: red
  text-decoration: none
  &:hover
    text-decoration: underline

SassMeister Gist

Parent selector reference

You may find it necessary to extend selectors within a rule. For example, you may need extend the styling of a button to designate a fail state.

In this case, you can explicitly specify where the parent selector should be inserted using the & character.

SCSS

button {
  background: gray;
  border: 1ps solid black;
  border-radius: 5px;
  &.fail {
    color: red;
    border-color: red;
  }
}

Sass

button
  background: gray
  border: 1ps solid black
  border-radius: 5px
  &.fail
    color: red
    border-color: red

SassMeister Gist

Selector prefixing

Sometimes it is necessary to prefix the rule you are engineering with another selector that appears higher up in the DOM. This becomes particularly useful when working with tools like Modernizer.

In this case, you can explicitly specify where the parent selector should be inserted by placing the selector before the & character.

SCSS

.box {
  box-sizing: border-box;
  width: 800px;
  padding: 30px;
  border: 1px solid black;
  .no-boxsizing & {
    width: 738px;
  }
}

Sass

.box
  box-sizing: border-box
  width: 800px
  padding: 30px
  border: 1px solid black
  .no-boxsizing &
    width: 738px

SassMeister Gist

Compound selector w/suffix

When using naming conventions like BEM for example, you may want to create selectors that inherit the primary selector's name. For this, the & must appear at the beginning of a compound selector, but it can be followed by a suffix that will be added to the parent selector.

SCSS

.block-name {
  &__element {
    color: red;
    &__element {
      color: orange;
    }
    &--modifer {
      color: yellow;
    }
  }
}

Sass

.block-name
  &__element
    color: red
    &__element
      color: orange
    &--modifer
      color: yellow