常用分组结构伪类
选择第一个元素
.list > li:nth-of-type(1) {
background-color: violet;
}
选择第一个元素
.list>li:first-of-type {
background-color: green;
}
:nth-of-type(1)===>:first-of-type
选择第8个元素
.list > li:nth-of-type(8) {
background-color: violet;
}
选择最后一个元素
.list>li:last-of-type {
background-color: yellow;
}
选中倒数第四个
.list>li:nth-last-of-type(4) {
background-color: red;
}
上下文选择器/层级选择器
语法:
层级:>,空格
平级:+,~
- 1.子元素选择器:>
- 2.后代元素:空额
- 3.相邻兄弟:+
- 4.所有兄弟:~
伪类选择器计算
公式与说明:
- :nth-of-type(an+b)
- a:系数,[0,1,2,…]
- n:[0,1,2,3,…]
- b: 偏移量,从0开始
- 注:计算出来的索引,必须有效,从1开始
实例1: 匹配第3个元素后面的所有兄弟元素
.list> :nth-of-type(n+3) {
background-color: green;
}
计算过程:
- 0+3=3
- 1+3=4
- 2+3=5
- …
实例2: 匹配倒数3个元素
.list> :nth-of-type(-n+3) {
background-color: green;
}
计算过程:
- -0+3=3
- -1+3=2
- -2+3=1
- -3+3=0