在多个父项中选择第n个子项 [英] Select nth-child across multiple parents
问题描述
我有以下标记:
<div class="foo">
<ul>
<li>one</li>
<li>two</li>
</ul>
<ul>
<li>three</li>
</ul>
<ul>
<li>four</li>
</ul>
</div>
我想打造one和three。
I wish to style "one" and "three".
但是,标记也可以是:
<div class="foo">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<ul>
<li>four</li>
</ul>
</div>
我尝试使用下列CSS:
I've tried using the following CSS:
.foo li:nth-child(1),
.foo li:nth-child(3)
{
color:red;
}
但是,正如所料,这是每个 ul
。 (演示: http://jsfiddle.net/hTfVu/ )
However, as expected, this is styling the first child of each ul
. (Demo: http://jsfiddle.net/hTfVu/)
如何更改我的CSS,以便我可以定位属于的第一个和第三个
? li
。 foo
How can I change my CSS so that I can target the 1st and 3rd li
belonging to .foo
?
推荐答案
你不能单独使用CSS选择器。 :nth-child()
和兄弟姐妹组合器仅限于共享相同父元素的子元素/兄弟元素,如其名称所隐含的,CSS选择器不能解释父元素-child结构,也没有任何像:nth-grandchild()
选择器(甚至 :nth-match()
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).
当然,像jQuery这样的东西变得微不足道: $('。foo li:eq(0),.foo li: eq(2)')
否则,你必须使用类或ID明确标记第一个和第三个 li
元素,然后选择它们。
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.
这篇关于在多个父项中选择第n个子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!