如何使用nth-child来选择除第一个元素以外的所有元素?

6
如何使用 :nth-child 操作符来选择给定 DIV 内的除第一个段落之外的所有段落?

:nth-child(/* select all but the first one */) {
     color: green;
}
<div>
    <p>Example 1</p>
    <p>Example 2</p>
    <p>Example 3</p>
    <p>Example 4</p>
    <p>Example 5</p>
    <p>Example 6</p>
    <p>Example 7</p>
</div>

3个回答

13
你可以使用以下公式:
:nth-child(n+1)

或者对于某些浏览器:

:nth-child(n+2)

来自W3Schools的说法:

使用公式(an + b)。描述:a代表循环大小,n是计数器(从0开始),b是偏移值。

链接

或者你可以为第一个元素使用单独的:first-child CSS声明。


3
请将其更改为n+2,否则它会针对所有元素,包括第一个。 - Dzhuneyt

6

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接