CSS伪类选择器奇偶匹配nth-child(even)
语法:
:nth-child(an+b)
下⾯就把CSS3标准中nth-child()⽤法⼤致介绍给⼤家:
CSS3伪类选择器:nth-child()
简单的归纳下nth-child()的⼏种⽤法。
jquery选择器和css选择器的区别第⼀种:简单数字序号写法
:nth-child(number)
直接匹配第number个元素。参数number必须为⼤于0的整数。
例⼦:
li:nth-child(3){background:blue;}
第⼆种:倍数写法
:nth-child(an)
匹配所有倍数为a的元素。其中参数an中的字母n不可缺省,它是倍数写法的标志,如3n、5n。
例⼦:
li:nth-child(3n){background:red;}
第三种:倍数分组匹配
:nth-child(an+b) 与 :nth-child(an-b)
先对元素进⾏分组,每组有a个,b为组内成员的序号,其中字母n和加号+不可缺省,位置不可调换,这是该写法的标志,其中a,b均为正整数或0。如3n+1、5n+1。但加号可以变为负号,此时匹配组内的第a-b个。(其实an前⾯也可以是负号,但留给下⼀部分讲。)
例⼦:
li:nth-child(3n+1){background:red;}
li:nth-child(3n+5){background:blue;}
li:nth-child(5n-1){background:yellow;}
li:nth-child(3n±0){background:green;}
li:nth-child(±0n+3){background:orange;}
第四种:反向倍数分组匹配
:nth-child(-an+b)
此处⼀负⼀正,均不可缺省,否则⽆意义。这时与:nth-child(an+1)相似,都是匹配第1个,但不同的是它是倒着算的,从第b个开始往回算,所以它所匹配的最多也不会超过b个。
例⼦:
li:nth-child(-3n+8){background:red;}
li:nth-child(-1n+8){background:blue;}
第五种:奇偶匹配
:nth-child(odd) 与 :nth-child(even)
分别匹配序号为奇数与偶数的元素。奇数(odd)与(2n+1)结果⼀样;偶数(even)与(2n+0)及(2n)结果⼀样。
作者观点:表格奇偶数⾏定义样式就可以写成
.table > tr:nth-child(even) > td {background-color: #f00;}  (偶数⾏)
.table > tr:nth-child(odd) > td {background-color: #c00;}  (奇数⾏)jQuery中⽤此⽅法可以实现条纹效果:
$("table tr:nth-child(even)").addClass("hangbg");
even 可以换成别的参数,上⾯介绍的五种情况都可以。
后⾯的addClass("hangbg") hangbg 是个CSS class名称。