:nth-child()和:nth-of-type()的区别:
:nth-child()和:nth-of-type()都是css3的伪类选择器
先上代码
<div class="nthDiv">
<div>div</div>
<p>p1</p>
<p>p2</p>
</div>
<style>
.nthDiv p:nth-child(2){
background: yellow;
}
.nthDiv p:nth-of-type(2){
background: #6cf;
}
</style>
效果图:

可以看到伪类选择器 :nth-child(2) 和 :nth-of-type(2) 括号中都是2,但指向的却是不同的元素。
是因为 .nthDiv p:nth-child(2) 选中的是.nthDiv子元素中的第二个,并且这个元素是p标签才会生效,而 .nthDiv p:nth-of-type(2) 选中的是.nthDiv子元素中的第二个p标签。
拓展:
可以运用数学表达式 2n 和 2n+1 批量选择处于单双位置的子元素(可以用于选择表格的单双行之类的)
示例:
<div class="nthDiv">
<p>单</p>
<p>双</p>
<p>单</p>
<p>双</p>
<p>单</p>
<p>双</p>
<p>单</p>
<p>双</p>
<p>单</p>
<p>双</p>
</div>
<style>
.nthDiv p:nth-of-type(2n + 1){
background: yellow;
}
.nthDiv p:nth-of-type(2n){
background: #6cf;
}
</style>
效果图:


被折叠的 条评论
为什么被折叠?



