:nth-​​child(even / odd)选择器与类 [英] :nth-child(even/odd) selector with class

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

问题描述



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



链接到jsFiddle



但颜色重置。



有办法吗?

解决方案

一般来说,你想要的是不可能的,但是有一种方法可以实现有限数量的排除元素的期望行为:一般同胞组合器



这个想法是每次出现非< - 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;
}

Link to 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 ~.

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

See it in action.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆