在我的 HTML 中,
<div class="container">
</div>
<div class="container">
</div>
<div class="container">
</div>
<div class="container">
</div>
..................
..................
在上面的 HTML 中,我有 container
类。在我的 CSS 中,我需要向 .container:nth-child(3,4,5,6,..and so on)
添加一些样式。意味着我需要应用除 1 和 2 之外的所有 nth-child
。
最佳答案
:nth-child()
不适用于类,它会查找元素本身。您需要用包装器包装 .container
div 并使用以下内容:
.wrapper div:nth-child(n+3) {
/* put your styles here... */
}
<div class="wrapper">
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
<div class="container"></div>
</div>
澄清 :nth-child()
使用 .container:nth-child(n+3)
可能有效也可能无效。因为,:nth-child()
伪类表示与选择器匹配的 nth
子元素(在本例中为 .container
)。
如果 .container
元素不是其 parent 的 nth-child,则不会被选中。
来自Spec :
The
:nth-child(an+b)
pseudo-class notation represents an element that hasan+b-1
siblings before it in the document tree, for any positive integer or zero value ofn
, and has a parent element.
考虑这个例子:
<div class="parent">
<div>1st</div>
<div>2nd</div>
<div>3rd</div>
<div class="container">4th</div>
<div class="container">5th</div>
<div class="container">6th</div>
<div>7th</div>
<div class="container">8th</div>
<div>9th</div>
</div>
在这种情况下,.container:nth-child(2)
不会选择第二个 div.container
元素(它有 5th
内容)。因为该元素不是其父元素的 2nd 子元素,在父元素的子元素树中。
此外,.container:nth-child(n+3)
将选择所有 div.container
元素,因为 n
从 0
表示父级子树中的第一个元素,第一个 div.container
是其父级的 4th child。
n starts from 0
n = 0: (0 + 3) = 3 => 3rd element
n = 1: (1 + 3) = 4 => 4th element
n = 2: (2 + 3) = 5 => 5th element
...
因此div.container:nth-child(n+3)
代表所有的3rd, 4th, 5th, ... 匹配 div.container
选择器的子元素。
关于html - 大于和小于的 CSS nth-child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035799/