&: parent selector

Referencing Parent Selectors: &

Sometimes it’s 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 or for when the body element has a certain class. In these cases, you can explicitly specify where the parent selector should be inserted using the & character. For example:

a {
  font-weight: bold;
  text-decoration: none;
  &:hover { text-decoration: underline; }
  body.firefox & { font-weight: normal; }
}

is compiled to:

a {
  font-weight: bold;
  text-decoration: none; }
  a:hover {
    text-decoration: underline; }
  body.firefox a {
    font-weight: normal; }

& will be replaced with the parent selector as it appears in the CSS. This means that if you have a deeply nested rule, the parent selector will be fully resolved before the & is replaced. For example:

#main {
  color: black;
  a {
    font-weight: bold;
    &:hover { color: red; }
  }
}

is compiled to:

#main {
  color: black; }
  #main a {
    font-weight: bold; }
    #main a:hover {
      color: red; }

& 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. For example:

#main {
  color: black;
  &-sidebar { border: 1px solid; }
}

is compiled to:

#main {
  color: black; }
  #main-sidebar {
    border: 1px solid; }

If the parent selector can’t have a suffix applied, Sass will throw an error.

doc_Sass
2016-11-11 13:08:56
Comments
Leave a Comment

Please login to continue.