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>
The :nth-of-type selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The :nth-of-type() pseudo-class represents an element that has an+b siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element.
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 div
element, 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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With