Țaman ŞheƦzad Țaman ŞheƦzad - 6 months ago 11
HTML Question

Targeting a class by jumping over divs?

In this html:

<div class="main">

<div class="container1">
<div class="div_1">
....
</div>
</div>

<div class="container2">
<div class="div_2">
....
</div>
</div>

</div>


I want to target the
div_2
like this

.main .container1 .container2 .div_2 {}


That means the target also has to go through the
container1
div to apply the css.

Why? This could be a very useful trick without using any scripts
for example targeting
div_2
on a page when
container1
exists while on another page does not exist so it does not work. Is this possible?

Answer

Use the adjacent sibling selector (+):

.main .container1 + .container2 .div_2 { 
  background-color: aqua;
}
<div class="main">
    <div class="container1">
        <div class="div_1">div_1</div>
    </div>
    <div class="container2">
        <div class="div_2">div_2</div>
    </div>
</div>

The selector above is saying: Target .div_2, that is a descendant of .container2, which immediately follows its sibling .container1, which is a descendant of .main.

References: