CSS Solution for selecting every other ancestor

Viewed 82

Is there a way I can make this text alternate in color using CSS. I tried using whatever:nth-child(odd) but it doesn't work for nested divs.

<div class="whatever">
this is some text
  <div class="whatever">
  this is some text
    <div class="whatever">
    this is some text
      <div class="whatever">
      this is some text
      </div>
    </div>
  </div>
</div>
4 Answers

You can use JavaScript for that:

var els = document.getElementsByClassName("whatever");
let even = false;
for (let i=0;i<els.length;i++) {
   if (!even) {
     els[i].style.color = "red"; 
   } else {
     els[i].style.color = "blue";
} 
even = !even;
}

You can achieve alternate color using nth-child selector. Please have a look at the code.

.whatever:nth-child(odd) {
        color: red;
      }
      .whatever:nth-child(even) {
        color: blue;
      }
<body>
    <div class="whatever">this is some text</div>
    <div class="whatever">this is some text</div>
    <div class="whatever">this is some text</div>
    <div class="whatever">this is some text</div>
  </body>

:nth-child(odd) method is use when there is multiple child divs but here in your case every div has single child that's why it's not working.

Case 1:

var elements = document.getElementsByClassName("whatever");

for (let i=0;i<elements.length;i++) {
   if (i%2==0) {
     elements[i].style.color = "Yellow"; 
    } else {
     elements[i].style.color = "Green";
     } 
}
<div class="whatever">
this is some text
  <div class="whatever">
  this is some text
    <div class="whatever">
    this is some text
      <div class="whatever">
      this is some text
      </div>
    </div>
  </div>
</div>

Case 2: If you want to change color of text using css then you can apply different class for that

.text-green{
color:green;
}

.whatever{
color:yellow
}
<div class="whatever">
this is some text
  <div class=" text-green">
  this is some text
    <div class="whatever">
    this is some text
      <div class=" text-green">
      this is some text
      </div>
    </div>
  </div>
</div>

Assign a class to every other <div> with the first color.

.red { color: red }

Then assign the child selector > to .red with the second color. This ensures that only the direct children are affected and the color doesn't cascade down any further.

.red > div { color: blue }

.red {
  color: red
}

.red > div {
  color: blue
}
<div class="x red">
  this is some text
  <div class="x">
    this is some text
    <div class="x red">
      this is some text
      <div class="x">
        this is some text
      </div>
    </div>
  </div>
</div>

Related