你能用nth-child选择最后3项并选择奇数或偶数吗?

时间:2012-10-12 11:25:49

标签: css css3 css-selectors

方案

比如说我有以下内容:

1 | 2 | 3
4 | 5 | 6
7 | 8 | 9

<ul>
    <li>1</li><li>2</li><li>3</li>
    <li>4</li><li>5</li><li>6</li>
    <li>7</li><li>8</li><li>9</li>
</ul>

我有奇数和偶数的默认背景:

li:nth-child(even) {
    background: #ff0000;
} 

li:nth-child(odd) {
    background: #00ff00;
}

问题

但是我想为后3个结果应用不同的背景,也取决于它们是偶数还是奇数:

li:nth-last-child(-n + 3)(even) {
    background: #0000ff;
}

li:nth-last-child(-n + 3)(odd) {
    background: #ffff00;
}

这可能吗?

1 个答案:

答案 0 :(得分:4)

您还需要重复:nth-child部分:

li:nth-last-child(-n + 3):nth-child(even) {
    background: #0000ff;
}

li:nth-last-child(-n + 3):nth-child(odd) {
    background: #ffff00;
}

此外,根据您拥有的元素数量,:nth-child(odd):nth-last-child(odd)(以及他们的even对应元素)可能会选择不同的元素。