connexo
connexo

Reputation: 56770

CSS: Target an element that has none of a list of classes

I would like to create a rule for certain elements which only affects an element if it has none of a list of classes.

My attempt:

div:not(.a, .c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

If you run this snippet, it obviously does not work as intended. Seems the selector is invalid and does not affect any div whatsoever.

Next I tried chaining :not() which seems very clumsy, but works:

div:not(.a):not(.c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

Is this the only way to solve the given problem?

Upvotes: 1

Views: 104

Answers (2)

Rounin
Rounin

Reputation: 29453

Chaining the :not() selector in CSS is the only way at present (in Jan 2020) to indicate a logical AND operator.

So, yes:

div:not(.a):not(.c)

is the correct way to write:

div:not(.a) AND div:not(.c)

div:not(.a):not(.c) {
  color: red;
}
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>

Upvotes: 1

T04435
T04435

Reputation: 13992

I think by your question you always know the classes you don't want to change the styles for. So assuming that this is my take at it.

.all {
  /** give default styles to all elements */
  color: red;
}

.a,
.c {
  /** then reset the ones you where targeting with :not():not()... */
  color: black;
}
<div class="all a">a</div>
<div class="all b">b</div>
<div class="all c">c</div>

Upvotes: 0

Related Questions