dots Created with Sketch.
Yogesh Chauhan's Blog

Ampersand (Parent Selector) in SCSS (Sass)

in SCSS on April 26, 2021

The parent selector is nothing but an ampersand symbol (&).

The parent selector (&) is used to refer to the outer selector when you nest selectors.

I love it! It makes it so much easier to reuse the outer selector and helps to create more complex styles by following a simple syntax.

For e.g. take a look at this SCSS:


.alert {
  &:hover {
    font-weight: bold;
  }
  &.second-class{
    font-size: 20px;
  }
}

Here’s the compiled CSS:


.alert:hover {
  font-weight: bold;
}
.alert.second-class {
  font-size: 20px;
}

Those are just two different elements/selectors style but can you imagine doing that for tons of nested elements?!

You can refer to the outer selector after as well. Like this:


.alert {
  :not(&) {
    opacity: 0.8;
  }
}

Here’s the compiled CSS:


:not(.alert) {
  opacity: 0.8;
}

If you don’t leave a space or add a bracket, you might experience weird behavior.

Here’s the GitHub issue page related to that.

Add Suffixes

Use the parent selector, you can add additional suffixes to the outer selector, as long as the outer selector ends with an alphanumeric name.

Like this:


.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;

  &__copy {
    display: none;
    padding: 1rem 1.5rem 2rem 1.5rem;
    color: gray;
    line-height: 1.6;
    font-size: 14px;
    font-weight: 500;

    &--open {
      display: block;
    }
  }
}

Compiled CSS will be this:


.accordion {
  max-width: 600px;
  margin: 4rem auto;
  width: 90%;
  font-family: "Raleway", sans-serif;
  background: #f4f4f4;
}
.accordion__copy {
  display: none;
  padding: 1rem 1.5rem 2rem 1.5rem;
  color: gray;
  line-height: 1.6;
  font-size: 14px;
  font-weight: 500;
}
.accordion__copy--open {
  display: block;
}

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
Debugging in WordPress Part 1: WP_DEBUGWordPressHow to use @if and @else in SCSS?SCSSClasses in JavaScript: The BasicsJavaScriptRelative Length Units in CSSCSSHow to create a pricing table using flex in CSS?CSSDoes :is() pseudo selector hint at CSS preprocessing in the future?CSS