简体   繁体   中英

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 , ie only available for children of .main ?

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

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
}

You could also use @at-root

%abstract {
  color: red;
}

.main {

  .main-element {
    @extend %abstract;

    @at-root .outside {
      @extend %abstract;
    }
  }
}

output

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

or just move the placeholder outside specific main block

%abstract {
    color: red;
  }

.main {

  .main-element {
    @extend %abstract;
  }
}

.outside {
  @extend %abstract;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM