I’m doing a little experiment, trying to alternate background colours for nested divs.
This is what I intend to achieve (without the inline styles):
<div style="background: #fff;">
<div style="background: #000;">
<div style="background: #fff;">
<div style="background: #000;">
and so on...
</div>
</div>
</div>
</div>
I feel like I must be missing something obvious! I tried div:nth-of-type(2n) but this appears to only apply on one level.
This is for an experiment where the divs are generated, so the solution needs to be endless (not something along the lines of div div div div = white). I know it’s quite easy with JavaScript, just looking for a pure CSS solution.
As Mr Lister pointed out, nth-of-type works on one level (that of the parent of the selected div).
As far as i know and after looking through the W3C CSS3 Selectors there doesn’t appear to be any css selectors for traversing through nesting (except the > selector, which only looks at the direct child of parent).
I would love te be proven wrong though as that could be very usefull.
So the only (css) solution would be the one you already stated:
div > div > div {background: white; }Can’t you just generate this along with the generation of the div’s?