【实测】CSS样式nth-child的灵活使用技巧及使用方法-Discuz教程下载

【实测】CSS样式nth-child的灵活使用技巧及使用方法

来自版块: Discuz教程发表于: 2023-7-25 14:20:43
1956
0
如本资源下载地址失效,请点击此处进行反馈
开通本站Svip会员,全站资源免费下
一、需求描述
在开发过程中,会碰到一些选择器的需求:
例如使列表中的第一项或者最后一项显示不同的样式 、列表中的奇数或者偶数项显示不同的背景色 . . . 等等。
我们可以通过 CSS 来实现这样的效果,CSS 给我们提供了几个样式参数:first-child、last-child、nth-child(n)。

二、使用方法的代码示例
1.常见使用方法
first-child first-child:选择列表中的第一个TAG.html" target="_blank" class="relatedlink">标签。

举例:第一行字体显示为红色,代码如下:
  1. li:first-child{color: red;}
复制代码
nth-child(n) nth-child(n):选择列表中的第 n 个标签。

举例:第三行字体显示为蓝色,代码如下:
  1. li:nth-child(3){color: blue;}
复制代码
nth-child(odd) nth-child(odd):选择列表的奇数行。

举例,奇数行背景显示为灰色,代码如下:
  1. li:nth-child(odd){ background: #999; }
复制代码
我们可以通过另外的方法选择奇数行,例如: nth-child(n+1) 、 nth-child(2n-1) 等。

代码如下:
  1. /*First*/
  2. li:nth-child(n+1){ background: #999; }
复制代码
  1. /*Second*/
  2. li:nth-child(2n-1){ background: #999; }
复制代码
nth-child(even) nth-child(even):选择列表的偶数行。

举例:偶数行背景显示为土黄色(不要在意那些细节),代码如下:
  1. li:nth-child(even){ background: #F6E0AF; }
复制代码
同样,我们可以通过另外的方法选择偶数行,例如: nth-child(2n) 。

代码如下:
  1. li:nth-child(2n){ background: #F6E0AF; }
复制代码
上面的几种方法运行效果如下图:
20200609210212327.png
2.更加灵活的使用方法
上面是几种比较常见的选择方法,我们还可以通过 CSS 更灵活的进行选择,有下面几种方法:

nth-child(-n+n) nth-child(-n+n):选择第 n 个之前的元素(此处的 n 是后面的那个,下同)。

举例:前三行背景色设置为绿色,代码如下:
  1. li:nth-child(-n+3){ background: #2cae1d; }
复制代码
nth-child(n+n) nth-child(n+n):选择第 n 个之后的元素。

举例:第五行及以后背景色设置为蓝色,代码如下:
  1. li:nth-child(n+5){ background: #0ab1fc; }
复制代码
nth-last-child(n) nth-last-child(n):选择倒数第 n 个元素。

举例:倒数第三元素字体设置为红色,代码如下:
  1. li:nth-last-child(3){ color: red; }
复制代码
同样可以使用上面的方法进行拓展,方法如下:

nth-last-child(n+n) nth-last-child(n+n):选择倒数第 n 个之前的元素。

举例:倒数第三个及之前的元素字体设置为粗体,代码如下:
  1. li:nth-last-child(n+3){ font-weight: bold; }
复制代码
上面的几种方法运行效果如下图:
2.png
nth-last-child(3n) nth-last-child(3n):选择第 3、6、. . . 个元素,选择三的倍数。

举例:第3、6、 . . . 三的倍数行背景色设置为橙色,代码如下:
  1. li:nth-child(3n){ background: orange; }
复制代码
nth-last-child(3n+1) nth-last-child(3n+1):选择第 1、4、7 个元素,从第一个开始每个递增三个。

举例:第1、4、7 . . . 行背景色设置为红色,代码如下:
  1. li:nth-child(3n+1){ background: red; }
复制代码
上面的几种方法运行效果如下图:
20200609210623824.png

全部评论 0

您需要登录后才可以回帖 立即登录
登录
0
0
0
返回顶部