优选主流主机商
任何主机均需规范使用

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;
        }

 

 

 

未经允许不得转载:搬瓦工中文网 » CSS nth-child() 选择器详解与实战案例:轻松掌握子元素定位技巧