Search code examples
cssscopesassextendplaceholder

Scope of the @extend-only selectors (placeholders) in SASS


I thought the following SCSS would end in error when compiling:

.main {

  %abstract {
    color: red;
  }

  .main-element {
    @extend %abstract;
  }

}

.outside {
  @extend %abstract; // <-- 
}

While it actually compiles to:

.main .main-element, .main .outside {
  color: red;
}

Is there any way to make such placeholders not available ouside the scope, i.e. only available for children of .main?

See http://sass-lang.com/documentation/file.SASS_REFERENCE.html#placeholders


Solution

  • You don't. Nesting only provides scope to variables (as of Sass 3.3) or mixins, not selectors. A placeholder class is the same as any other class, except for the part where its name is not output in the compiled CSS.

    If this behavior is required, then you're stuck using mixins (which can, in turn extend the desired selector)

    %foo {
      color: red;
    }
    
    .main {
    
      @mixin foo() {
        @extend %foo;
      }
    
      .main-element {
        @include foo();
      }
    
    }
    
    .outside {
      @include foo(); // <-- yep, it errors here
    }