【问题标题】:nth-child targeting all child elements [duplicate]nth-child 针对所有子元素[重复]
【发布时间】:2019-12-31 22:05:34
【问题描述】:

我有以下演示:

#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>

我原以为只有父元素的第一个子元素是蓝色的,但实际上它们都是蓝色的。这是为什么呢?

【问题讨论】:

    标签: html css


    【解决方案1】:

    The problem in your case is the way :nth-child works,基本上你需要在子级/兄弟级添加它,而不是在父级(因为你的parent没有什么不同,你的选择器基本上就像#parent一样)。使用选择器的方式,它就像#parent 是您要选择的第一个孩子,这就是为什么它都是蓝色的。稍作改动就可以了:

    #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 &gt; div:nth-child(1)

    【讨论】:

    • 可能值得注意的是,这将适用于每个第一次出现的div,它是#parent 的后代,而不仅仅是直系孩子。
    • @George 好点!
    【解决方案2】:

    这是因为你在 CSS 中选择了父元素,但没有选择其子名称的元素。试试这个,希望对你有帮助。

    #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>

    【讨论】:

    • 只是因为你在 css 中选择了父级,但没有选择子名的元素。试试这个,希望对你有帮助。谢谢
    • 欢迎马赫什!您应该将您的解释放在答案的正文中,而不是添加评论;发布后您仍然可以edit答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多