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
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 bothclass="b d"
which is a child of some element ofclass="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 eitherclass="b"orclass="d"(or both)
which is a child of some element ofclass="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.
3 Comments
.d is a child of .a. In fact, something could match both selectors with .a being either a descendant or ancestor of .d..c and .e.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
> and ~ combinators; see my answer.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.