nth-child doesn't respond to class
There's no way to filter by class in CSS because there's no :nth-of-class()
selector. One way around this is to put your two different kinds of div
s into their own groups, then select based on those groups. For example:
<div class="orange">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="red">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
With this selector:
div.red div:nth-child(2) {
background: red;
}
Regarding the last bit of your question:
And I don't understand why nth-child() and nth-of-type() respond differently, since there are only eight tags of the same type in the document.
For the code you give there shouldn't be any difference. I tested it, and the two pseudo-classes work as expected. But, in general:
:nth-child()
operates on an entire level of siblings without regard for any other simple selectors. Then if the nth child is not among what's matched by the simple selectors, nothing is matched.
:nth-of-type()
operates on a level of siblings of the given type without regard for other simple selectors. Then if the nth element occurring of that type is not among what's matched by the simple selectors, nothing is matched.
You can use the general sibling combinator:
div,
div.red ~ div.red ~ div.red {
background: gray;
}
div.red ~ div.red {
background: red;
}
It is verbose and you need to reset the styles back again, but it could be useful in some special situations.
It could be automated with a CSS preprocessor, and if I understand gzip correctly, since the CSS ouput is just repeating the same text the gziped file size should not be terribly big unless you use it a lot.
there's a simpler solution that I have found to work with my divs without any special lines of code.
.red div:nth-child(6) {background-color:#ccc;}
.red div:nth-child(9) {background-color:#eee;}
works just fine as well without the div in front.