在多个父母中选择第 n 个孩子 [英] Select nth-child across multiple parents

查看:25
本文介绍了在多个父母中选择第 n 个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下标记:

<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".

但是,标记也可以是:

<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 以便可以定位属于 .foo 的第一个和第三个 li?

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

推荐答案

你不能单独使用 CSS 选择器.:nth-child() 和兄弟组合器仅限于共享相同父级的子级/兄弟级,正如它们的名称所暗示的那样,CSS 选择器不能解释父子结构中的这种变化,也不能有类似 :nth-grandchild() 选择器(甚至 :nth-match() from Selectors 4 将自身限制为仅共享同一父级的元素.

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)') 否则你必须标记第一个和第三个 li 元素显式使用类或 ID,然后选择它们.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆