:nth-child(偶数/奇数) 选择器与类

:nth-child(even/odd) selector with class(:nth-child(偶数/奇数) 选择器与类)

本文介绍了:nth-child(偶数/奇数) 选择器与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to apply odd/even selectors to all elements in a list with the class parent.

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;
}

链接到 jsFiddle

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

But the colors are resetting. I want the list items to be the color of the text.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

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

In general what you want is not possible, but there is a way to achieve the desired behavior for limited numbers of "excluded" elements: the general sibling combinator ~.

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

The idea is that for each occurrence of a non-.parent element subsequent .parent elements will have their colors toggled:

.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;
}

实际操作.

当然,人们愿意接受这一点是有限度的,但它与纯 CSS 所能达到的一样接近.

Of course there is a limit to how far one would be willing to take this, but it's as close as you can get with pure CSS.

这篇关于:nth-child(偶数/奇数) 选择器与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为::nth-child(偶数/奇数) 选择器与类