<分区>
我有以下演示:
#parent:nth-child(1) {
color: blue;
}
<html>
<body>
<div id="parent">
<div>first child</div>
<div>second child</div>
<div>third child</div>
</div>
</body>
</html>
我原以为只有父元素的第一个子元素是蓝色的,但实际上它们都是。这是为什么?
<分区>
我有以下演示:
#parent:nth-child(1) {
color: blue;
}
<html>
<body>
<div id="parent">
<div>first child</div>
<div>second child</div>
<div>third child</div>
</div>
</body>
</html>
我原以为只有父元素的第一个子元素是蓝色的,但实际上它们都是。这是为什么?
最佳答案
The problem in your case is the way :nth-child
works , 基本上你需要在子级/兄弟级添加它,而不是在父级(因为你的 parent
没有什么不同,你的选择器基本上就像 #parent
).使用您拥有的选择器,它就好像#parent 是您要选择的第一个 child ,这就是为什么它全是蓝色的。稍微改变一下就可以了:
#parent div:nth-child(1) {
color: blue;
}
<html>
<body>
<div id="parent">
<div>first child</div>
<div>second child</div>
<div>third child</div>
</div>
</body>
</html>
另外,作为 George下面刚刚提到,这将适用于 #parent
的后代的任何第一个 div 事件,在您的情况下它没有区别,但它可能具有不同的结构,因此如果您只想将其限制为直接后代,您可以使用更具体的选择器 #parent > div:nth-child(1)
关于html - nth-child 定位所有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57679515/