Search code examples
sass

Prevent combination of multiple selectors


I'm trying to group all my vendor-specific stuff into a placeholder selector like this:

%search-bar-placeholder {
    color: red;
}

.search-bar::-webkit-input-placeholder {
    @extend %search-bar-placeholder;
}

.search-bar:-moz-placeholder {
    @extend %search-bar-placeholder;
}

.search-bar::-moz-placeholder {
    @extend %search-bar-placeholder;
}

.search-bar:-ms-input-placeholder {  
    @extend %search-bar-placeholder;
}

And then it compiles to this:

.search-bar::-webkit-input-placeholder, .search-bar:-moz-placeholder, .search-bar::-moz-placeholder, .search-bar:-ms-input-placeholder {
  color: red; }

How can I make sure Sass doesn't put all the selectors together ? Like this:

.search-bar::-webkit-input-placeholder {
    color: red;
}

.search-bar:-moz-placeholder {
    color: red;
}

.search-bar::-moz-placeholder {
    color: red;
}

.search-bar:-ms-input-placeholder {  
    color: red;
}

Solution

  • When looking at Extend/Inheritance at sass-lang.com it seems that the selectors will always be comma separated. Even if you add another property, it will keep the shared properties in the comma separated list, and add another selector just for that overridden value.

    The way I achieved what you want is by using a mixin. Though it's not really the purpose of a mixin, it does get the job done. Your style is still centralized and you can print it out in each selector using a one liner too.

    @mixin placeholder-properties() {
      color: red;
      font-weight: bold;
    }
    
    .search-bar::-webkit-input-placeholder {
       @include placeholder-properties();
    }
    
    .search-bar:-moz-placeholder {
      @include placeholder-properties();
    }
    
    .search-bar::-moz-placeholder {
      @include placeholder-properties();
    }
    
    .search-bar:-ms-input-placeholder {  
      @include placeholder-properties();
    }
    

    The result will the following.

    .search-bar::-webkit-input-placeholder {
      color: red;
      font-weight: bold;
    }
    
    .search-bar:-moz-placeholder {
      color: red;
      font-weight: bold;
    }
    
    .search-bar::-moz-placeholder {
      color: red;
      font-weight: bold;
    }
    
    .search-bar:-ms-input-placeholder {
      color: red;
      font-weight: bold;
    }
    

    Here's a fiddle.