5

Is it possible to group two selectors so that an element is matched only if both selectors are satisfied? For example, if I want the element to satisfy both the selectors .a>.b~.c and .d~.e, is it possible to write a selector that matches the intersection of these selectors?

3 Answers 3

3

If you're using class selectors as in your example, you can chain classes like this:

.a > .b.d ~ .c.e

Selects an element that has both class="c e"
which is a sibling of (i.e. comes, directly or not, after) an element that has both class="b d"
which is a child of some element of class="a"

Or, like this, if you want .c.e to occur after an element that has either class b or d:

.a > .b ~ .c.e, .a > .d ~ .c.e

Selects an element that has both class="c e"
which is a sibling of an element with either class="b" or class="d" (or both)
which is a child of some element of class="a"

Both selectors imply that .b, .d and .c.e are all children of .a. I should also think it gives you the class selector intersection that you're looking for.

Sign up to request clarification or add additional context in comments.

3 Comments

Nothing in @ccy's post implies that .d is a child of .a. In fact, something could match both selectors with .a being either a descendant or ancestor of .d.
@Jacob Since the target element matches both selectors then that implies that it has both c and e classes, and from that it follows that both b and d are older siblings, and that a is their parent.
@Jacob: Exactly what Neil said. Remember, the OP wants an intersection of both selectors; the key element has to have both classes .c and .e.
2

No, you cannot do set intersection in CSS selectors. Sometimes you can find a way to combine two selectors into one that solves your specific problem, but I don't think there's a way to combine your two sample selectors.

1 Comment

Given OP's sample selectors, it should be possible due to the nature of the > and ~ combinators; see my answer.
1

I think BoltClock is on the right lines but to match exactly both the selectors given you need

.a > .b ~ .d ~ .c.e, .a > .b.d ~ .c.e, .a > .d ~ .b ~ .c.e {
}

since we have no information as to the relative positioning of b and d.

2 Comments

.a > .b ~ .c.e, .a > .d ~ .c.e would satisfy all of them methinks. Note that ~ means .c.e doesn't have to immediately follow .b or .d, unlike +.
I know, but .c.e still has to follow both .b and .d in an unspecified order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.