一、 首先注意一点: nth-of-type(n)和nth-child(n) 这里的n都是1开始的,不是0
二、讲一下 nth-of-type和nth-child 查找方式
1. select:th-of-type(n)
根据select选择器找到一个dom元素(假设叫el1) ====>在同级兄弟节点找type和el1的type相同节点(这里type指dom的类型,如div、p、span等)====> 找到第n个元素 ====> 判断这个元素是否满足select选择器,如果满足样式生效,不满足不生效
2. select:th-child(n)
根据select选择器找到一个dom元素(假设叫el1) ====>找到同级兄弟节点====> 找到第n个元素 ====> 判断这个元素是否满足select选择器,如果满足样式生效,不满足不生效
三、nth-of-type和nth-child的区别
他们的区别就是上面标红部分,重点体现在type 和 child,一个要求type相同,一个只要是同级的child就可以
四、举栗子 —— last-child为什么不生效?
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
<div class="child">8</div>
<div>我是type的干扰</div>
<p>我是child的干扰,我不会干扰type</p>
</div>
<style lang="scss" scoped>
.child{
height: 50px;
margin-bottom: 10px;
background-color: blue;
}
.child:last-of-type{
background-color: red;
}
</style>
.child:last-of-type 没有生效,因为最后一个元素是 <div>我是type的干扰</div> ,他没有.child 的class
.child:last-of-child没有生效,因为最后一个元素是 <p> ,他没有.child 的class
五、常用的表达方式
1. :nth-of-type(n) 第n个; 对应的:nth-child(n)
2. :last-of-type、:first-of-type 最后一个、第一个; 对应的:last-child、:first-child
3. :nth-of-type(odd) 第奇数个 even-偶数; 对应的 :nth-child(odd)
4. :nth-last-of-type(n) 倒数第n个; 对应的 :nth-last-child(n)
5. :nth-of-type(An + B) n从0开始,A与B都是固定的整数,可以是负数,但计算结果小于1的都会被忽略, 同样适用 :nth-child
:nth-of-type(2n) 匹配 2、4、6 其实相当于 even
:nth-of-type(2n + 1) 匹配 1、3、5 其实相当于 odd
:nth-of-type(3n + 2) 匹配 2、5、8 从2开始间隔3
:nth-of-type(-n + 5) 匹配前5个
6. 与 :not() 联合使用
.child:not(:last-of-type) 除最后一个元素以外的