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前面加了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>
这个也不难理解就是按照类型来计算,碰到一个同类型就加1,那你肯定会说既然如此那有什么好说的,关键如果像下面这样呢,如下:
.item:nth-of-type{color:red}
<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>
可以看到这里是选中了两个的,不同类型会被当作多类,只要符合选择器规范都会选中。
总结
nth-child
按照个数来算。
nth-of-type
按照类型来计算,如果是class那么碰到不同类型的,单独一类,符合条件的选中。
注意以下用法nth-child和nth-of-type的区别
1、first-child
first-child表示选择列表中的第一个标签。代码如下:
li:first-child{background:#090}
上面的意思是,li 列表中的 第一个li模块的背景颜色。
2、last-child
last-child表示选择列表中的最后一个标签,代码如下:
li:last-child{background:#090}
3、nth-child(3)
表示选择列表中的第3个标签,代码如下:
li:nth-child(3){background:#090}
上面代码中的3也可以改成其它数字,如4、5等。想选择第几个标签,就填写几。
4、nth-child(2n)
这个表示选择列表中的偶数标签,即选择 第2、第4、第6…… 标签。
5、nth-child(2n-1)
这个表示选择列表中的奇数标签,即选择 第1、第3、第5、第7……标签。
6、nth-child(n+3)
这个表示选择列表中的标签从第3个开始到最后(包括3)。
7、nth-child(-n+3)
这个表示选择列表中的标签从1到3,即小于3的标签(不包括3)。
8、nth-last-child(3)
这个表示选择列表中的倒数第3个标签。