彻底理解nth-child和nth-of-type的区别

1,126 阅读1分钟

主要是因为之前觉得自己已经理解了nth-of-type但后来发现好像和自己之前理解的不太一样,于是打算写下来。

nth-child

nth-child倒很好理解,就是选择第几个.

<style>
  p:nth-child(2),p:nth-child(7){
    color:red;
  }
</style>
<h1>标题</h1>
<p>这是锻若</p>
<p>这是锻若</p>
<span>这是span</span>
<span>这是span</span>
<span>这是span</span>
<p>这是锻若</p>

nth-child

可以看出nth-child是根据元素的个数来计算的,尽管我们在:nth-child前面加了p。这个没啥好说的。

nth-of-type

它说的是按照类型来选择,意思很简单但要是不研究一下还真容易理解错,看下面这个例子。

<style>
  p:nth-of-type(1),p:nth-of-type(3){
    color:red;
  }
</style>
<h1>标题</h1>
<p>这是锻若</p>
<p>这是锻若</p>
<span>这是span</span>
<span>这是span</span>
<span>这是span</span>
<p>这是锻若</p>

nth-of-type

这个也不难理解就是按照类型来计算的,碰到一个同类型就加1,那你肯定会说既然如此那有什么好说的,关键如果像下面这样呢,如下:

<style>
  .item:nth-of-type(3){
    color:red;
  }
</style>
<h1>标题</h1>
<p class="item">这是锻若</p>
<p>这是锻若</p>
<span>这是span</span>
<span class="item">这是span</span>
<span class="item">这是span</span>
<p class="item">这是锻若</p>
<p class="item">这是锻若</p>
<p class="item">这是锻若</p>

可以看到这里是选中了两个的,不同类型会被当作多类,p标签和span标签各自一类;只要符合选择器规范都会选中,额,好像有点简单哈,主要是这个例子写的太好了。就这样。还是总结一下吧。

总结一下

  • nth-child:按照个数来算。
  • nth-of-type:按照类型来计算,如果是class那么碰到不同类型的,单独一类,符合条件的选中。