CSS - how to color odd and even divs?

I want to use CSS to achieve the following effect without hard coding.

.colour-blue {
  color:blue;
}
.colour-light-blue {
  color:lightblue;
}
<div class="activeContent">
  <div class="content">
    <div class="colour-blue">
      odd div
    </div>
  </div>
  <div class="content">
    <div class="colour-light-blue">
      even div
    </div>
  </div>
  <!-- and more (content) div -->
</div>
Run code

How to do this using only pure CSS? I want to not manually assign a color class to each div

+4
source share
2 answers

You can do something like this:

.content:nth-child(odd)>div {
  background: blue;
}

.content:nth-child(even)>div {
  background: red;
}

.content {
  width: 200px;
  height: 200px;
}
<div class="activeContent">
  <div class="content">
    <div class="colour-blue">
      stuff
    </div>
  </div>

  <div class="content">
    <div class="colour-light-blue">
      some more stuff
    </div>
  </div>
</div>
Run code

This will work very well, I think.

+11
source

you can try the following:

.activeContent div.content:nth-child(2n) {
  color: #00ff00;
}

.activeContent div.content:nth-child(2n+1) {
  color: #0000ff;
}
<div class="activeContent">
  <div class="content">
    stuff
  </div>

  <div class="content">
    some more stuff
  </div>
  
  <div class="content">
    more and more stuff
  </div>
  
  <div class="content">
    one more stuff
  </div>
</div>
Run code
+6
source

Source: https://habr.com/ru/post/1686506/


All Articles