Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
355 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...