Coder Perfect

CSS Selector “(A or B) and C”?


This should be straightforward, but I’m having difficulties locating the appropriate search terms. Let’s pretend I’m in possession of

<div class="a c">Foo</div>
<div class="b c">Bar</div>

How can I construct a selection in CSS that matches “(.a or.b) and.c”?

I know I’m capable of completing this task:

.a.c,.b.c {
  /* CSS stuff */

Is there a better syntax if I’m going to have to do this type of logic a lot, with a variety of logical combinations?

Asked by Josh

Solution #1

No, the CSS operator (,) does not allow for groupings. Because it is the logical operator with the lowest precedence in selectors, you must employ it. a.c,.b.c.

Answered by Matt Ball

Solution #2

Not yet, however there is a pseudo-class selector called experimental:is() (formerly:matches()) that accomplishes exactly that:

:is.a .b) .c {
  /* stuff goes here */

More information can be found here and here. Most browsers now support its original version:any(), which functions in the same way, but will be superseded by:is in the future (). We’ll have to wait a little longer until we can use it everywhere (I surely will).

Answered by Metalcoder

Solution #3

I was able to achieve success by utilizing the:is() selector:

*:is(.a, .b).c{...}

Answered by Yaakov Bressler

Solution #4

If you’ve got this:

<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>

You could write: If you just want to choose elements with.x and (.a or.b), you could write:

.x:not(.c) { ... }

However, this is only useful if you have three “sub-classes” and only wish to select two of them.

Choosing only one subclass (for example,.a): .a.x

Choosing two subclasses (for example,.a and.b): .x:not(.c)


Answered by Šime Vidas

Solution #5

No, the type of thing you’re seeking for isn’t available in standard CSS.

However, you should investigate LESS and SASS.

These are two projects that aim to improve default CSS syntax by adding new capabilities such as variables, nested rules, and other improvements.

They both allow you to write far more organized CSS code, and they will almost probably fix your specific problem.

Of course, none of the browsers accept their expanded syntax (especially given the two projects’ syntax and capabilities are so dissimilar), but they do provide a “compiler” that turns your LESS or SASS code to regular CSS, which you can then use on your site.

Answered by Spudley

Post is based on