:nth-child(even/odd) selector with class(: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(偶数/奇数) 选择器与类


- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01