CSS 中 nth-child 和 nth-of-type 的区别

假设有如下代码结构,想要查找 Piggy 那个 p

<section>
   <h1>Words</h1>
   <p>Little</p>
   <p>Piggy</p>    <!-- Want this one -->
</section>

使用 nth-child 是不正确的:

p:nth-child(2) { color: red; } /* Now incorrect */

使用 nth-of-type 是正确的 :

p:nth-of-type(2) { color: red; } /* Still works */

即:

nth-child 用人话讲:

1. 查找某个p元素

2. 这个元素是它父级节点的第二个元素

nth-of-type 用人话讲:

1. 查找所有p元素中第二个p元素

原文链接: https://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/

原文地址:https://www.cnblogs.com/savokiss/p/6667801.html