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> <div>nothing</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> </div>22 Answers
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> <div>nothing</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> </div>0How 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> <span>nothing</span> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> <div>Test 1</div> </div>