1

Let's say I have the following bit:

<div class="class1 class2">...</div>
<div class="class1 ...">...</div>

Is there a way to make an SCSS rule that goes something like "for elements with class class1 and any other classes but class2 apply these properties". So if by default the divs would have a blue background, I would be able to write something like this and make all divs that are class1, but not class2, have a red background.

.class1 && !.class2 { // invented syntax, of course
    background-color: red;
}

I know there are other ways of achieving this, but I'm curious to know if you can somehow do it this way.

Xzenon
  • 1,193
  • 2
  • 15
  • 37

1 Answers1

1

This does not need a complex sass solution. You can simply use the css :not() selector. See the example below -

.class1{
    color: red;
}

.class1:not(.class2){
    color: green;
}
<div class="class1 class2">
  class1 and class2
</div>
<div class="class1">
  class1 but not class2
</div>

EDIT - The above snippet may work fine, but it may behave strangely in the below scenerio -

.class1:not(.class2){
    color: green;
}

.class1{
    color: red;
}

.class2{
    color: blue;
}

.class3{
    color: black;
}
<div class="class1 class2">
  class1 and class2
</div>
<div class="class1">
  class1 but not class2
</div>
<div class="class1 class3">
  class1 and class 3 but not class2
</div>

The .class3 selector comes later in the css, but still the color of text in third div stays green. It is because the :not() selector has more specificity. To deal with this, you will have to use id instead of class like below -

.class1:not(.class2){
    color: green;
}

.class1{
    color: red;
}

.class2{
    color: blue;
}

#id3{
    color: black;
}
<div class="class1 class2">
  class1 and class2
</div>
<div class="class1">
  class1 but not class2
</div>
<div class="class1" id="id3">
  class1 and class 3 but not class2
</div>

So concluding, the :not() pseudo selector will work fine for your situation, but you will have to take care of the specificity of selectors.

Praneet Dixit
  • 1,393
  • 9
  • 25