css3选择器:nth-child和nth-of-type之间的差别

时间:2023-01-01 23:34:02

<section>

<p>我是第1个p标签</p>

<p>我是第2个p标签</p>

</section>

然后对应2个选择器对应的CSS代码如下:

p:nth_child(2) { color:red;}

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

两种对应的效果都是这样的:

css3选择器:nth-child和nth-of-type之间的差别

对于:nth-child选择器有两点需要说明:

1,这个是个段落元素

2,这个是父级元素的第二个孩子

而对于:nth-of-type选择器,意味着选择一个元素如果:

1,选择父级元素的第二个  段落    子   元素

如果把上面的代码稍微修改一下:

<section>

<div>我是一个普通的div标签</div>

<p>我是第一个p标签</p>

<p>我是第二个p标签</p>

</section>

这个时候,p:nth-child(2) { color:red;} 并没有选择上任何的元素 ,所以并没有变化。

p:nth-of-type(2) { color:red;} 的显示结果是:

css3选择器:nth-child和nth-of-type之间的差别