This example contains two complex selectors, both using the subsequent-sibling combinator: .foo p ~ span and .foo p ~ .foo span.
- The first complex selector,
.foo p ~ span, matches all spans that come after a paragraph if the span and paragraph share the same parent and that parent or an ancestor of that parent has the class .foo. - The second complex selector,
.foo p ~ .foo span, matches all spans that are a descendant of the element with class .foo if that element is a sibling of the previously mentioned paragraph.
The example below shows that the target element in the complex selector must share the same parent as the initial element in the complex selector.
<h1>Dream big</h1>
<span>And yet again this is a red span!</span>
<div class="foo">
<p>Here is another paragraph.</p>
<span>A blue span</span>
<div class="foo">
<span>A green span</span>
</div>
</div>
.foo p ~ span {
color: blue;
}
.foo p ~ .foo span {
color: green;
}
In the above HTML, the two siblings of .foo p are span and .foo. The green span is a descendant of the .foo class, which is a sibling of p.
- When the target selector is
span, the span element that is a sibling of p is selected. The p element is a descendant of .foo, so are its span siblings. - In
.foo p ~ .foo span, the target selector is span that is a descendant of .foo. In this case, the span element that's a descendant of .foo is selected if that .foo is a sibling of p; essentially, both are nested in an ancestor of .foo.