.test:nth-child(1),
.test:nth-child(2),
.test:nth-child(3) {
color: #0F0
}
<div class="test">
<p>Test</p>
</div>
<div class="reuinIt">
<p>Test</p>
</div>
<div class="test">
<p>Test</p>
</div>
<div class="test">
<p>Test</p>
</div>
https://jsfiddle.net/dkfj2xzj/13/ <- UPDATED 如果有帮助,我的 jQuery 代码
为什么不跳过 .ruinIt
类而不是针对第三个 .test
?
我正在添加 <div>
s 是动态的,当一个 <div>
没有 .checkDrop
添加了类,我需要跳过它。
谢谢
最佳答案
这是因为 nth-child
选择器并不意味着它是该特定类的 nth。这意味着它是第 nth 个 sibling 。
所以 nth-child(2)
指的是你的 .reuinIt
类,但是,它也没有 .test
类,因此它不会收到任何样式。
你的最后 .test
类是 nth-child(4)
然而,它没有应用任何样式规则。
如果您想查看工作示例,我已经更新了您的 fiddle here .
例子
第n个 child
这里要记住的重要一点是 :nth-child
选择器根据容器/父元素内的索引/位置专门针对 HTML 元素。
看看下面的例子,注意相应的评论 :nth-child
选择器的索引会继续递增,而不管其针对的元素类型如何。
<div id="container">
<h1>Heading 1</h1> <!-- h1:nth-child(1) -->
<p>Paragraph 1</p> <!-- p:nth-child(2) -->
<p>Paragraph 2</p> <!-- p:nth-child(3) -->
<h2>Heading 2</h2> <!-- h2:nth-child(4) -->
<p>Paragraph 3</p> <!-- p:nth-child(5) -->
</div>
:nth-of-type
关于 :nth-of-type
的酷事是它忽略了所有其他类型不同的元素,即如果您定位的元素是 <p>
,它会在计算其索引时忽略所有周围的“非 <p>
”元素。
以下示例将使您对 :nth-of-type
的索引规则有一个基本的了解。如下:
<div id="container">
<h1>Heading 1</h1> <!-- h1:nth-of-type(1) -->
<p>Paragraph 1</p> <!-- p:nth-of-type(1) -->
<p>Paragraph 2</p> <!-- p:nth-of-type(2) -->
<h2>Heading 2</h2> <!-- h2:nth-of-type(1) -->
<p>Paragraph 3</p> <!-- p:nth-of-type(3) -->
</div>
使用 :nth-of-type 稍微复杂一些
然而,请务必记住 :nth-of-type
它的索引值基于 HTML 元素类型,而不管您用来调用该属性的 CSS 类。
看看下面的例子:
<div id="container">
<h1>Heading 1</h1> <!-- h1:nth-of-type(1) -->
<p class="my-class">Paragraph 1</p> <!-- .my-class:nth-of-type(1) -->
<p>Paragraph 2</p> <!-- p:nth-of-type(2) -->
<h2 class="my-class">Heading 2</h2> <!-- .my-class:nth-of-type(1) -->
<p class="my-class">Paragraph 3</p> <!-- .my-class:nth-of-type(3) -->
<h1 class="my-class">Heading 3</h1> <!-- .my-class:nth-of-type(2) -->
</div>
这个示例有点复杂,但如果您将 CSS 声明视为一种过滤规则,它会有所帮助。例如,如果通过键入以下内容创建 CSS 声明:
p:nth-of-type(2) {
background-color: red;
}
我实际上是在告诉浏览器两件事:
- 仅
<p>
标签应该受到影响, - 仅当它们是第二个时
<p>
在他们的 sibling 中标记
当我编写如下所示的 CSS 时,困难就来了:
.my-class:nth-of-type(1) {
background-color: red;
}
通过不指定元素类型,我的规则基本上使用以下过滤器读取:
- 只有类为
my-class
的元素应该受到影响, - 仅当这些元素是其元素类型的第一个兄弟元素时。
如果将上述 CSS 应用到示例中的 HTML (see fiddle for working example),我们将得到如下所示的输出:
在上面的输出中,您会看到第一个 <h2>
第一个<p>
无论他们的 sibling 是否拥有my-class
,元素都会受到影响。已应用类名。
关于html - 第 n 个 child 没有针对正确的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505023/