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;
}


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Solution for the error Commit failed – exit code 1 received in Desktop GithubMiscellaneousLIKE and ILIKE Operators in PostgresPostgresHow to implement NSNumberFormatter in Swift for currency?SwiftCurrencyPipe in Angular 9 with ExamplesAngularAND, OR and NOT boolean operators in Envision BasicEnvision BasicHow to set default timezone using PHP?PHP