Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the CSS adjacent selector based on nested child classes?

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

.a:has(.b .c) + .a .b .c
.a:has(.b .c) + .a .b .c {
  background-color: red;
}
<div class="a">
  <div class="b">
    <div class="c">1</div>
  </div>
</div>
<div class="a">
  <div class="b">
    <div class="c">2</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading