Controlling scope in nested Sass selectors

brianmcallister

Brian Wm. McAllister

Posted on December 11, 2020

Controlling scope in nested Sass selectors

There's a few tricks that you can use to control scope when nesting Sass selectors. The best use case I've been able to find is when you're writing selectors with BEM.

.block {
  $this: &; // <-- Here's the trick.

  &--modified {
    #{$this}__nested-block {
      some: style;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

...which will compile to:

.block--modified .block__nested-block { some: style; }
Enter fullscreen mode Exit fullscreen mode

If you had instead written this as:

.block {  
  &--modified {
    &__nested-block {
      some: style;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

...you would end up with:

.block--modified__nested-block { some: style; }
Enter fullscreen mode Exit fullscreen mode

which is probably not what you intended.

See more tips like this at Lab49's engineering micro-blog, called "Today, We Learned". Visit this specific post right here: https://twl.lab49.com/username/brian-mcallister-lab49/f8de1041bbd8c960c6d5b0b70c14580f

💖 💪 🙅 🚩
brianmcallister
Brian Wm. McAllister

Posted on December 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related