DEV Community

loading...
Lab49

Controlling scope in nested Sass selectors

Brian Wm. McAllister
Originally published at twl.lab49.com ・1 min read

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

Discussion (0)