:带有类的第n个子(偶数/奇数)选择器

nil*_*lsi 19 html css html5 css-selectors css3

我正在尝试将奇数/偶数选择器应用于类父类的列表中的所有元素.

HTML:

<ul>
    <li class="parent">green</li>
    <li class="parent">red</li>
    <li>ho ho ho</li>
    <li class="parent">green</li>
    <li class="parent">red</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

.parent:nth-child(odd) {
    background-color: green;
}

.parent:nth-child(even) {
    background-color: red;
}

ul {
    width:100px;
    height: 100px;
    display: block;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

链接到jsFiddle

但颜色正在重置.我希望列表项是文本的颜色.

有没有办法做到这一点?

Jon*_*Jon 21

一般来说,你想要的是不可能的,但是有一种方法可以为有限数量的"排除"元素实现所需的行为:一般的兄弟组合 ~.

这个想法是,对于每个非.parent元素的出现,后续.parent元素的颜色都会被切换:

.parent:nth-child(odd) {
    background-color: green;
}
.parent:nth-child(even) {
    background-color: red;
}

/* after the first non-.parent, toggle colors */
li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: red;
}
li:not(.parent) ~ .parent:nth-child(even) {
    background-color: green;
}

/* after the second non-.parent, toggle again */
li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: green;
}
li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(even) {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

看到它在行动.

当然,人们愿意花多少钱来限制它,但它与纯CSS一样接近.


Sco*_*ttS 10

这是一种常见的误解

:nth-child:nth-of-type选择不看"类"或其他任何计数.它们只查看(1)所有元素,或(2)某个"类型"的所有元素(不是,不是属性,只是元素的类型 - div或者li等等).

所以你不能在没有了解你的确切html结构的情况下用纯CSS跳过它(然后,只有当你正在处理一些元素时 - 请参阅Jon的答案,你需要知道有多少非您正在处理的元素,正如您所看到的,他注意到实际限制非常小,或者使用javascript.


Ily*_*syn 6

只有CSS Selectors 4才能进行第n次匹配.

在现有的CSS中,只能在一些有限的情况下使用一般兄弟组合器多次,例如在@ Jon的答案中,甚至以更"机械"的方式(例子):

.parent,
.parent ~ .parent ~ .parent,
.parent ~ .parent ~ .parent ~ .parent ~ .parent,
.parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent
{
    background-color: green;
}

.parent ~ .parent,
.parent ~ .parent ~ .parent ~ .parent,
.parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent,
.parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent
{
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

在实践中,我似乎更好地使用JS/jQuery.