CSS伪类选择器 奇偶匹配nth 您所在的位置:网站首页 手机怎么制作png CSS伪类选择器 奇偶匹配nth

CSS伪类选择器 奇偶匹配nth

2023-12-14 14:04| 来源: 网络整理| 查看: 265

语法:

:nth-child(an+b)

下面就把CSS3标准中nth-child()用法大致介绍给大家: 

CSS3伪类选择器:nth-child() 简单的归纳下nth-child()的几种用法。

第一种:简单数字序号写法

: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名称。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有