HTML入门之常用伪类选择器的使用方法总结
16lz
2022-03-23
常用分组结构伪类
选择第一个元素
.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
语法糖
- 奇数(odd)
- 偶数(even)
实例3:匹配奇数列
等效于.list> :nth-of-type(odd) {
background-color: lightgreen;
}
计算过程:.list> :nth-of-type(2n -1) {
background-color: lightgreen;
}
- 2*0-1=-1
- 2*1-1=1
- 2*2-1=3
- 2*3-1=5
- …
实例4:匹配偶数列
.list> :nth-of-type(even) {
background-color: lightgreen;
}
更多相关文章
- Android开发手记一 NDK编程实例
- 无废话Android之常见adb指令、电话拨号器、点击事件的4种写法、
- android中activity的四种加载模式
- Android上使用ksoap2支持Web Service服务调用实例
- Android(安卓)Google Map实例 - 在地图和卫星图之间切换(Android
- Android中Handler与Message的简单实例
- Android中的Context
- gravity和layout_gravity
- Android开发实例详解之IMF(Android(安卓)SDK Sample—SoftKeyboar