CSS Selector "(A or B) and C"?
This should be simple, but I'm having trouble finding the search terms for it.
Let's say I have this:
<div class="a c">Foo</div>
<div class="b c">Bar</div>
In CSS, how can I create a selector that matches something that matches "(.a or .b) and .c"?
I know I could do this:
.a.c,.b.c {
/* CSS stuff */
}
But, assuming I'm going to have to do this sort of logic a lot, with a variety of logical combinations, is there a better syntax?
is there a better syntax?
No. CSS' or
operator (,
) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c
.
Not yet, but there is the experimental :is()
(formerly :matches()
) pseudo-class selector that does just that:
:is.a .b) .c {
/* stuff goes here */
}
You can find more info on it here and here. Currently, most browsers support its initial version :any()
, which works the same way, but will be replaced by :is()
. We just have to wait a little more before using this everywhere (I surely will).
For those reading this >= 2021:
I found success using the :is()
selector:
*:is(.a, .b).c{...}
If you have this:
<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>
And you only want to select the elements which have .x
and (.a
or .b
), you could write:
.x:not(.c) { ... }
but that's convenient only when you have three "sub-classes" and you want to select two of them.
Selecting only one sub-class (for instance .a
): .a.x
Selecting two sub-classes (for instance .a
and .b
): .x:not(.c)
Selecting all three sub-classes: .x