html - :nth-child(even/odd) selector with class

标签 html css css-selectors

<分区>

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

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

enter image description here

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 所能达到的最接近的水平。

关于html - :nth-child(even/odd) selector with class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17458582/

相关文章:

html - 为什么这些样式不会导致单行标题和居中页面内容?

css float 和边框问题

css - 在不知道父级下的位置的情况下选择了类的第一个实例

html - 多个最后一个 child 选择

html - 因为必要的 div 阻止它们成为 sibling ,所以坚持尝试在其他元素悬停时更改元素?

html - 在媒体查询中下载 Assets

javascript - 通过 JS 函数在选择选项中使用单元格添加行

html - Bootstrap 中的垂直居中搜索框

css - "Center left"与 css 对齐

javascript - Javascript/html 中的多个 onclick 事件