伪类nth-child问题

为什么下面:nth-child(1)和:nth-child(2)文字全红, 当:nth-child(3)开始就显示正常

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        :nth-child(1) {
            color: red;
        }
    </style>
</head>
<body>
    <div>
        <p>文字内容1</p>
        <p>文字内容2</p>
        <p>文字内容3</p>
        <p>文字内容4</p>
        <p>文字内容5</p>
        <p>文字内容6</p>
        <p>文字内容7</p>
        <p>文字内容8</p>
    </div>

    <strong>外层1</strong>
    <strong>外层2</strong>
    <strong>外层3</strong>
</body>
</html>

image.png

阅读 2.1k
3 个回答

测试了一下,由于没有设置标签类型和color可继承
1的时候,div匹配该样式
2的时候,body匹配了该样式

前面应该有个 * 的,你省略了,表示匹配任意元素。

document
  html // document:nth-child(1)
    head 
    body // html:nth-child(2)
      div // body:nth-child(1)
        p
        p
        p
      strong
      strong
      strong

指定标签去使用

p:nth-child(1) {
    color: red;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题