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/

 

posted @ 2017-04-05 11:02  savokiss  阅读(169)  评论(0编辑  收藏  举报