SASS: 有没有办法添加一个可选的选择器?

SASS: Is there a way to add an optional selector?

我的想法是可选地添加一个 CSS-Selector 到 mixin 中已经存在的选择器堆栈。

我的愿望

@mixin myMixin(mobileSelector:true) {
  @if(mobileSelector) {
    .foo .mobile:before,
  }
  .classXY .subclass:before{
    color: red;
  }
}

.awesomeClass-A {
  @include myMixin();
}

@media (min-width: 1025px){
  .awesomeClass-B {
    @include myMixin(false);
  }
}

应编译为:

 
.awesomeClass-A .foo .mobile:before,
.awesomeClass-A .classXY .subclass:before {
    color: red;
}

@media (min-width: 1025px) {
  .awesomeClass-B .classXY .subclass:before {
    color: red;
  }
}

如何获得这项工作? :)

只需在$之前调用变量并将整个class添加到@if条件:


@mixin myMixin($mobileSelector: true) {
  @if ($mobileSelector) {
    .foo .mobile:before,
    .classXY subclass:before {
      color: red;
    }
  } @else {
    .classXY subclass:before {
      color: red;
    }
  }
}

.awesomeClass-A {
  @include myMixin();
}

@media (min-width: 1025px) {
  .awesomeClass-B {
    @include myMixin(false);
  }
}

您可以使用变量和插值语法:

@mixin myMixin($mobileSelector: true) {
  $mobile: if($mobileSelector, ".foo .mobile:before,","");
  #{$mobile} .classXY .subclass:before{
    color: red;
  }
}

.awesomeClass-A {
  @include myMixin();
}

@media (min-width: 1025px){
  .awesomeClass-B {
    @include myMixin(false);
  }
}