html - 大于和小于的 CSS nth-child

标签 html css css-selectors

在我的 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>

Working Demo .

澄清 :nth-child()

使用 .container:nth-child(n+3) 可能有效也可能无效。因为,:nth-child() 伪类表示与选择器匹配的 nth 子元素(在本例中为 .container)。

如果 .container 元素不是其 parentnth-child,则不会被选中。

来自Spec :

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, 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 元素,因为 n0 表示父级子树中的第一个元素,第一个 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 选择器的子元素。

Online Demo .

关于html - 大于和小于的 CSS nth-child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035799/

相关文章:

jquery - 带有 JQuery 的菜单中的 CSS Sprites 问题

python - 如何使用 Selenium 和 Python 选择具有不可选择的 ="on"属性的 kendo 下拉元素

html - 设置一行 DIV 中最后一个 DIV 的样式

html - CSS 显示正确但在刷新之前不正确, float 问题

c# - 在 WPF TextBlock 中显示 XAML 格式的文本

jquery - 将div放在浏览器底部

html - 如何更改 HTML 中链接标签文本的颜色?

javascript - HTML img src 不动态更新

html - 如何在整个单元格上拉伸(stretch)链接?

css - 从 Bootstrap 中删除 Glyphicons