Search code examples
csssassdart-sass

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


my idea is to add optionally a CSS-Selector to already existing selector stack inside a mixin.

My wish

@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);
  }
}

Should compile to:

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

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

How to get this work? :)


Solution

  • You could use a variable and interpolation syntax:

    @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);
      }
    }