CSS 选择器 nth-child 的几种用法

1,799 阅读1分钟

开发过程中会碰到一些选择器的要求 比如选择第一项,或者第几项 或者最后一项这些常见的用法

   first-child 
   first-child:选择列表中的第一个标签。
   
   last-child
   last-child:选择列表中的最后一个标签。
   
   nth-child(n)
   nth-child(n):选择列表中的第 n 个标签。
   
   nth-child(odd)
   nth-child(odd):选择列表的奇数行。
   
   我们可以通过另外的方法选择奇数行,例如: nth-child(n+1) 、 nth-child(2n-1) 等。
   
   nth-child(even)
   nth-child(even):选择列表的偶数行。
   
   同样,我们可以通过另外的方法选择奇数行,例如: nth-child(2n) 。

上面是几种比较常见的选择方法,我们还可以通过 CSS 更灵活的进行选择,有下面几种方法:

   nth-child(-n+n) 
   nth-child(-n+n):选择第 n 个之前的元素(此处的 n 是后面的那个下同 第二个N是具体数字)。
   
   nth-child(n+n)
   nth-child(n+n):选择第 n 个之后的元素。
   
   nth-last-child(n) 
   nth-last-child(n):选择倒数第 n 个元素。
   
   nth-last-child(n+n)
   nth-last-child(n+n):选择倒数第 n 个之前的元素。
   
   nth-last-child(3n) 
   nth-last-child(3n):选择第 3、6、. . .  个元素,选择三的倍数。