我正在尝试将奇数/偶数选择器应用于具有父类的列表中的所有元素。
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>
CSS:
.parent:nth-child(odd) {
background-color: green;
}
.parent:nth-child(even) {
background-color: red;
}
ul {
width:100px;
height: 100px;
display: block;
}
Link to jsFiddle
但是颜色正在重置。我希望列表项是文本的颜色。
有办法吗?
一般来说,你想要的是不可能的,但有一种方法可以为有限数量的“排除”元素实现所需的行为:general sibling combinator ~
。
这个想法是,对于每次出现的非 .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;
}
See it in action .
当然,人们愿意走多远是有限制的,但它是纯 CSS 所能达到的最接近的水平。