I can use the adjacent selector like this:
/* When c and c are adjacent, color the second c red */
.c + .c {
background-color: red;
}
But how to do the same thing when the ".c" is nested?
<div class="a">
<div class="b">
<div class="c"></div>
</div>
</div>
<div class="a">
<div class="b">
<div class="c"></div>
</div>
</div>
/* Does not work */
.a .b .c + .a .b .c {
background-color: red;
}
3
Answers
For adjacent selector
+
, the two selectors must be on the same level.So it must be
.a + .a
, since they are the only adjacent elements in your snippet. Then you can select the second.a
‘s child element:.a + .a .b .c
. After that you could restrict the first.a
to make sure it also has child elements.b .c
using:has()
pseudo class:CSS doesn’t provide a way to select elements as you requested. However, if possible, modify the HTML structure to accommodate this (such as adding a class or attribute to the container of
.c
). If unable to alter the HTML structure, you can use JavaScript or jQuery to accomplish this.Without the ability to modify the HTML structure or use JavaScript or jQuery, I’m afraid there’s no way to achieve this solely with CSS.
In that case you can’t access .c directly by adjacent selector.
Because the adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".
So, in this case you can use + for targeting .a and then .c like below: