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?
Not yet, but there is the experimental
:matches()
pseudo-class function that does just that: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:matches()
. We just have to wait a little more before using this everywhere (I surely will).No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.
If you have this:
And you only want to select the elements which have
.x
and (.a
or.b
), you could write: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
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
.