首页 - web前端开发

css选择器:nth-child()的相关用法

前言
:nth-child() 选择器,该选择器选取父元素的第 N 个子元素,与类型无关,公式通用。

一、列表中的偶数标签 :nth-child(2n)
 
    /* 偶数 */
    li:nth-child(2n) {
      color: skyblue;
    }


二、列表中的奇数标签 :nth-child(2n+1)
  // 奇数 
  li:nth-child(2n+1) {
      color: skyblue;
    }


三、选择从第6个开始,直到最后 :nth-child(n+6)
  /* 选择从第6个开始,直到最后 */
    li:nth-child(n+6) {
      color: skyblue;
    }


四、选择第1个到第6个 :nth-child(-n+6)
 /* 选择第1个到第6个  */
    li:nth-child(-n+6) {
      color: pink;
    }


五、选择第6个到第9个
  /* 选择第3个到第6个  */
    li:nth-child(n+3):nth-child(-n+6) {
      color: pink;
    }
 

 六、补充 :nth-of-type(n)
:nth-of-type(n) 选择器匹配属于父元素的特定类型的第 N 个子元素的每个元素,n 可以是数字、关键词或公式。

 
    /* 补充 :nth-of-type(n) */
    li:nth-of-type(2n+1) {
      color: violet;
    }
七、从倒数第六个开始变色
 /* 倒数第六个开始变色 */
    li:nth-last-child(-n+6) {
      color: aqua;
    }