1、第几个元素

li:nth-child(1)
{
  background: #ff0000;
  border-bottom: 1px;
}
li:nth-child(2)
{
  background: #ff0000;
  border-bottom: 1px;
}

2、奇数、偶数

li:nth-child(odd)
{
  background:#ff0000;
}
li:nth-child(even)
{
  background:#0000ff;
}

3、倍数

li:nth-child(2n)
{
  background: #ff0000;
  border-bottom: 1px;
}

4、公式:隔选择子元素,选择1,4,7,10

li:nth-child(3n+1)
{
  background: #ff0000;
  border-bottom: 1px;
}

5、正方向范围,选中从第6个开始的子元素

li:nth-child(n+6)
{
  background: #ff0000;
  border-bottom: 1px;
}

6、负方向范围,选中从第1个到第9个子元素。使用 :nth-child(-n+9) ,就相当让你选中第9个和其之前的所有子元素

li:nth-child(-n+9)
{
  background: #ff0000;
  border-bottom: 1px;
}

7、前后限制范围,选择第6个到第9个

li:nth-child(n+6):nth-child(-n+9)
{
  background: #ff0000;
  border-bottom: 1px;
}

8、范围高级用法:选中的子元素是从第2位到第9位,并且只包含奇数位。

li: nth-child(n+2):nth-child(odd):nth-child(-n+9)
{
  background: #ff0000;
  border-bottom: 1px;
}

9、最后一个元素开始计数

li:nth-last-child(2)
{
  background: #ff0000;
  border-bottom: 1px;
}

10、first-child 选择列表中的第一个标签

li:first-child
{
  background: #ff0000;
  border-bottom: 1px;
}

11、last-child 选择列表中的最后一个标签

li:last-child
{
  background: #ff0000;
  border-bottom: 1px;
}

12、nth-of-type是取当前元素的兄弟元素的第n个,nth-child取的是当前元素的第n个节点的当前元素(上图说明)

13、nth-of-type()、:nth-last-of-type()、first-of-type、last-of-type相关用法参考nth-child()

作者 铁血 汉子 2023年6月9日
2024/04/18/10:22:12am 2023/6/9/6:08:57
0 315