:nth-child(even / odd)选择器与类 [英] :nth-child(even/odd) selector with class
问题描述
HTML:
$ b $ b
< ul>
< li class =parent>绿色< / li>
< li class =parent>红< / li>
< li> ho ho ho< / li>
< li class =parent>绿色< / li>
< li class =parent>红色< / li>
< / ul>
CSS:
code> .parent:nth-child(odd){
background-color:green;
}
.parent:nth-child(even){
background-color:red;
}
ul {
width:100px;
height:100px;
display:block;
}
但颜色重置。
有办法吗?
一般来说,你想要的是不可能的,但是有一种方法可以实现有限数量的排除元素的期望行为:一般同胞组合器 〜
。
这个想法是每次出现非< - code> .parent 元素后续 .parent
元素
.parent:nth-child(odd){
background-color:green;
}
.parent:nth-child(even){
background-color:red;
}
/ *第一个非.parent,切换颜色之后* /
li:not(.parent)〜.parent:nth-child(odd){
background-color:red;
}
li:not(.parent)〜.parent:nth-child(even){
background-color:green;
}
/ *在第二个非.parent之后,再次切换* /
li:not(.parent)〜li:not(.parent)〜.parent: nth-child(odd){
background-color:green;
}
li:不是(.parent)〜li:not(.parent)〜.parent:nth-child(even){
background-color:red;
}
。当然,有多少人愿意接受这个限制,但是它就像你可以用纯CSS一样接近。
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;
}
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 ~
.
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;
}
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(even / odd)选择器与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!