skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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:

    .a + .a .b .c{
        background-color: red;
    }
    <div class="a">
        <div class="b">
            <div class="c">First C</div>
        </div>
    </div>
    <div class="a">
        <div class="b">
            <div class="c">Second C</div>
        </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search