8

It works perfectly if I remove the first div.

But if I have the first div without the class, it doesn't work correctly.

Test 1 should be blue and the next test should be red, and so on.

When I have another div, it doesn't work correctly. How do I solve this issue?

.el:nth-of-type(odd) {
  background-color: blue;
}
.el:nth-of-type(even) {
  background-color: red;
}
<div id="content">
  <div>nothing</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
waisie li
  • 343
  • 1
  • 4
  • 15
  • http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class/8539107#8539107 This one might also answer your question – Zim84 Sep 28 '16 at 20:34
  • Could you have a variable number of divs without the el class at the top? – j08691 Sep 28 '16 at 20:35

2 Answers2

10

In your particular case, you could simply reverse the CSS rules for odd and even nth-of-type (see snippet). The nth-of-type refers to the tag, i.e. the divelement, not the class, therefore also counting the first div which doesn't have a class.

Since your CSS rule selectors combine the class with the nth-of-type, the first div isn't affected, since it doesn't have a class, yet the counting for odd or even starts at the first div.

.el:nth-of-type(odd) {
 background-color: red;
}

.el:nth-of-type(even) {
 background-color: blue;
}
<div id="content">
    <div>nothing</div>
    <div class="el">Test 1</div>
    <div class="el">Test 1</div>
    <div class="el">Test 1</div>
    <div class="el">Test 1</div>
    <div class="el">Test 1</div>
    <div class="el">Test 1</div>
    </div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
2

How do I solve this issue?

Change the first div to another element, so it gets skipped by nth-of-type.

.el:nth-of-type(odd) {
  background-color: blue;
}
.el:nth-of-type(even) {
  background-color: red;
}
<div id="content">
  <span>nothing</span>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
  <div class="el">Test 1</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701