<!--例如:ul.list-->
<ul class="list">
<li class="li">item1</li>
<li class="li">item1</li>
<li class="li">item2</li>
<li class="li">item3</li>
<li class="li">item4</li>
<li class="li">item5</li>
<li class="li">item6</li>
<li class="li">item7</li>
<li class="li">item8</li>
</ul>
作用:用来匹配子元素,给一个查询起点起点
例如:ul.list
.list > li.first{
background: lightgreen;
}
/* 用伪类匹配第1个*/
.list > li:nth-of-type(1){
background: lightgreen;
}
/* 用伪类匹配第2个*/
.list > li:nth-of-type(2){
background: lightgreen;
}
/* 用伪类匹配第一个: [first-of-type] */
.list > li:first-of-type{
background: lightgreen;
}
/* 用伪类匹配最后一个: [last-of-type] */
.list > li:last-of-type{
background: lightgreen;
}
! :nth-of-type(an+b)
* 1. a: 参数,[0,1,2,3,...]
* 2. n: 参数,[0,1,2,3,...]
* 3. b: 偏移量,[从0开始]
/* 规则:计算出来的索引,必须是有效的(从1开始) */
/* 1. 匹配第1个 */
.list > li:nth-of-type(0n+1){
background: lightgreen;
}
.list > li:nth-of-type(1){
background: lightblue;
}
/* 2. 匹配第3个*/
.list > li:nth-of-type(0n+1){
background: lightgreen;
}
/*
1. 0*0 + 3 = 3
2. 0*1 + 3 = 3
...
所以可以简写 nth-of-type(3)
*/
/* 1. 全选 1n */
.list > li:nth-of-type(1n+0){
background: lightgreen;
}
/* 2. 全选 + 偏移量 1n + 3 :从第3个开始全选 */
.list > li:nth-of-type(1n+3){
background: lightgreen;
}
/* 计算结果
* 1: 1 * 0 + 3 =3
* 2: 1 * 1 + 3 =4
* 3: 1 * 2 + 3 =5
...
以此类推,取完所有有效的索引
*/
.list > li:nth-of-type(-n+3){
background: lightgreen;
}
/* 计算结果
* 1: -1 * 0 + 3 =3
* 2: -1 * 1 + 3 =2
* 3: -1 * 2 + 3 =1
* 3: -1 * 2 + 3 =0 无效索引,结束
以此类推,取完所有有效的索引
*/
* a = 0: 匹配一个
* a = 1: 匹配一组(正向相邻元素)
* a = -1:匹配一组(反向相邻元素)
* a > 1: 格行匹配(a为间隔行数)
.list > li:nth-of-type(n){
background-color:transparent;
}
.list > li:nth-of-type(2n){
background: -lightgreen;
}
.list > li:nth-of-type(2n+1){
background: -lightgreen;
}
/*
1. 偶数索引: even <==> 2n
2. 奇数索引: odd <==> 2n+1/2n-1
*/
.list > li:nth-of-type(even){
background: -lightgreen;
}
.list > li:nth-of-type(odd){
background: -lightgreen;
}
.list > li:nth-of-type(odd):hover{
background: -lightgreen;
手形光标
cursor: pointer;
延迟0.5秒
transition: 0.5s;
}
/* 将选择器 nth-of-type() 换成 nth-last-child() */
.list > li:nth-last-child(-n+3){
background: lightgreen;
}
* 1. nth-of-type(an+b)
* 2. nth-last-of-type(an+b)
* 3. nth-last-child(an+b)
* 4. first-of-type
* 5. last-of-type
更多MDN,可以参考