DaPrae DaPrae - 1 month ago 6
CSS Question

nth-of-type not working unless html element changed

I'm being driven mad by this problem. I'm trying to target every other instance of a div with a particular class by using nth-of-type. I've gotten nth-of-type to work when the HTMl elements are changed up but not when it's just divs. It must be that I'm not understanding something right so I appreciate your help with this!

Here's an example, close to what I need (except the inner section tags should be divs):



.employee-group {
border: 1px solid green;
}

.employee-group:nth-of-type(odd) {
background-color: blue;
}






<div class="employee-group">
<p class="employee">Odd</p>
<p class="employee">Div</p>
</div>
<section>
<p>Section</p>
</section>
<div class="employee-group">
<p class="employee">Even .employee-group</p>
<p class="employee">Works as expected, no background color</p>
</div>
<section>
<p>Section</p>
</section>
<div class="employee-group">
<p class="employee">Odd</p>
<p class="employee">Div</p>
</div>
<section>
<p>Section</p>
</section>



http://codepen.io/usern4me/pen/BLZjJj

And here is the scenario that I need to make work but for the life of me I can't do it:



.employee-group {
border: 1px solid green;
}

.employee-group:nth-of-type(odd) {
background-color: blue;
}






<div class="employee-group">
<p class="employee">Odd</p>
<p class="employee">Div</p>
</div>
<div>
<p>Even</p>
<p>Div</p>
</div>
<div class="employee-group">
<p class="employee">Odd div</p>
<p class="employee">But even .employee-group (shouldn't have bg color!!!)</p>
</div>
<div>
<p>Even</p>
<p>Div</p>
</div>
<div class="employee-group">
<p class="employee">Odd</p>
<p class="employee">Div</p>
</div>
<div>
<p>Even</p>
<p>Div</p>
</div>



http://codepen.io/usern4me/pen/YGbwEb

It seems like the nth-type-of selector is matching the class and that it's an odd div in the total amount of divs. I would expect it to just solely look at the class for the count.

Thanks for your help!

Answer

For the even .employee-group issue change the .employee-group:nth-of-type(odd) to

.employee-group:nth-of-type(4n+1)

Explaination: Your requirement wanted to skip every other item within a odd sequence i.e. instead of (1,3,5,7,9,11....) the properties should hit (1,5,9,13....) etc. To do that we gave the parameter a formula to calculate that so what the css does is takes the index (0,1,2,3) as n for each .employee-group element and calculates where to apply the properties based on formula result which goes as

(4n+1) = target number

(4x0+1)= 1

(4x1+1)= 5

(4x2+1)= 9

(4x3+1)= 13

...and so on.

That should solve your problem i believe.

Hope this helps.