Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

css - Select nth-child across multiple parents

I have the following markup:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
    </ul>
    <ul>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

I wish to style "one" and "three".

However, the markup could also be:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

I've tried using the following CSS:

.foo li:nth-child(1),
.foo li:nth-child(3)
{
    color:red;
}

However, as expected, this is styling the first child of each ul. (Demo: http://jsfiddle.net/hTfVu/)

How can I change my CSS so that I can target the 1st and 3rd li belonging to .foo?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can't do that with CSS selectors alone. :nth-child() and sibling combinators are limited to children/siblings sharing the same parent only, as implied by their names, and CSS selectors cannot account for such variations in parent-child structure, nor is there anything like an :nth-grandchild() selector (even :nth-match() from Selectors 4 limits itself to elements sharing the same parent only).

Of course with something like jQuery it becomes trivial: $('.foo li:eq(0), .foo li:eq(2)') Otherwise you'll have to mark the first and third li elements explicitly using classes or IDs, and then select them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...