如果孩子的总数是偶数,如何将样式添加到倒数第二?

not*_*off 1 css css-selectors css3

所以,我有一个动态数量的列表项,我想将样式应用到倒数第二个....如果只有偶数个元素.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我想在上面的例子中将样式应用于Three li元素,但如果如下则没有.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ier 7

你可以结合:nth-child(odd):nth-last-child(2).

这是有效的,因为:nth-last-child(2)它将选择倒数第二个子节点,并且:nth-child(odd)仅在奇数时选择它.如果孩子的总数是偶数,则倒数第二个孩子总是奇数.

ul li:nth-child(odd):nth-last-child(2) {
  color: #f00;
}
Run Code Online (Sandbox Code Playgroud)
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
Run Code Online (Sandbox Code Playgroud)


Har*_*rry 7

您可以使用两个选择器的组合,如下面的代码段所示.

当父元素具有偶数个子元素时,第二个最后一个元素必须是奇数编号的元素,因此如果元素与两个元素匹配nth-last-child(2),nth-child(odd)则表示它是父元素的第二个子元素,父元素的偶数为元素.

li:nth-last-child(2):nth-child(odd) {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
Run Code Online (Sandbox Code Playgroud)