:有子类的nth-child(偶/奇)select器

我试图将奇数/偶数select器应用于父类的列表中的所有元素。

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

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

有没有办法做到这一点?

一般来说,你想要的是不可能的,但是有一种方法可以实现有限数量的“排除”元素的期望行为: 一般的兄弟组合子 ~

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

看到它的行动

当然,有多less人愿意接受这一点是有限制的,但是和纯CSS一样可以达到这个目标。

这是一种常见的误解

:nth-child:nth-of-typeselect者不会看“阶级”或其他任何东西来计算。 他们只查看(1)所有元素,或者(2)某个“types”的所有元素(不是 ,不是属性 ,只不过是元素的typesdivli等)。

所以,如果不知道自己的html结构是否正确,那么就不能使用纯CSS来跳过它(然后,只有事实上存在一些你正在处理的内容 – 参见Jon的答案,你需要知道有多less非 – 你正在处理的元素,正如你所看到的,他注意到实际的限制是非常小的),或者使用javascript。

只有使用CSSselect器4才可能有n匹配 。

在现有的CSS中,只能在一些有限的情况下使用通用的兄弟组合器多次,就像在@ Jon的回答中一样,或者甚至以更“机械的”方式( 例子 ):

 .parent, .parent ~ .parent ~ .parent, .parent ~ .parent ~ .parent ~ .parent ~ .parent, .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent { background-color: green; } .parent ~ .parent, .parent ~ .parent ~ .parent ~ .parent, .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent, .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent ~ .parent { background-color: red; } 

在实践中,对我来说使用JS / jQuery好像更好。

CSS

另一种可靠的方式来复制这个目前是与邻接兄弟select器:

 .parent, .parent + .parent + .parent, .parent + .parent + .parent + .parent + .parent /* etc */ { background-color: green; } .parent + .parent, .parent + .parent + .parent + .parent /* etc */ { background-color: red; } 

你有三个select:

  • 使用not()select器。 这将使您的突出显示持续下去,但偶尔会翻转突出显示的顺序 。 如果您的列表可能包含您要突出显示的元素的巨大分组,请使用此选项。
  • 使用+ (邻接兄弟)select器。 此选项不会无限期地保持突出显示 ,但它保证了订单永远不会被翻转。 如果您的清单将突出显示的元素组合在一起,请使用此选项。
  • 使用~ (任何兄弟)select器。 我不会推荐这个,因为列表将无法基于总列表长度正确地突出显示,而不是完全匹配的兄弟 。 这在其他两个选项之前总是会失败,而且更明显。

小提琴: http : //jsfiddle.net/corymcd/kVcZJ/

随意从这里复制HTML并粘贴到其他人演示他们的方法。

jQuery的

如前所述,使用像jQuery这样的东西很容易让你分配你的元素甚至/奇怪的类或只是改变内联样式。

 // Find all objects to highlight, remove all of the highlighting classes, // and then re-highlight. $(".parent").removeClass('odd even').each(function(index) { var objPrev = $(this).prev('.parent'); if( objPrev.hasClass('odd') ) { $(this).addClass('even'); } else { $(this).addClass('odd'); } }); 

小提琴在这里: http : //jsfiddle.net/corymcd/kAPvX