CSS-结构伪类详解

346 阅读2分钟

1. nth-child

:nth-child(an+b)  这个CSS 伪类首先找到所有当前元素的兄弟元素,然后按照位置先后顺序从1开始排序,选择的结果为CSS伪类:nth-child括号中表达式(an+b)匹配到的元素集合(n=0,1,2,3...)

注意: an 必须写在 b 的前面,不能写成 b+an 的形式!!!

  • :nth-child(1)

    • 是父元素中的第1个子元素
  • :nth-child(2n)

    • n代表任意正整数和0

    • 是父元素中的第偶数个子元素(第2、4、6、8......个)

    • 跟:nth-child(even)同义

  • :nth-child(2n + 1)

    • n代表任意正整数和0

    • 是父元素中的第奇数个子元素(第1、3、5、7......个)

    • 跟:nth-child(odd)同义

  • :nth-child(-n + 2)

    • 代表前2个子元素
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    ul li:nth-child(3) {
      color: red;
    }

    /* 0, 1, 2, 3, 4, 5...... */
    ul li:nth-child(2n) {
      color: green;
    }

    /* 奇数 */
    ul li:nth-child(2n + 1) {
      color: blue;
    }


    /* 每4个一组的第一个 */
    div > div:nth-child(4n + 1) {
      color: orange;
    }

    div > div:nth-child(4n + 2) {
      color: purple;
    }

    div > div:nth-child(4n + 3) {
      color: red;
    }

    div > div:nth-child(4n) {
      color: blue;
    }

    /* 前5个 */
    div > div:nth-child(-n + 5) {
      font-size: 20px;
    }

  </style>
</head>
<body>

  <ul>
    <li>列表元素1</li>
    <li>列表元素2</li>
    <li>列表元素3</li>
    <li>列表元素4</li>
    <li>列表元素5</li>
    <li>列表元素6</li>
  </ul>

  <div>
    <div>列表元素1</div>
    <div>列表元素2</div>
    <div>列表元素3</div>
    <div>列表元素4</div>
    <div>列表元素5</div>
    <div>列表元素6</div>
    <div>列表元素7</div>
    <div>列表元素8</div>
    <div>列表元素9</div>
    <div>列表元素10</div>
  </div>

</body>
</html>

nth-child.png

2. nth-last-child

:nth-last-child()的语法跟:nth-child()类似,不同点是:nth-last-child()最后一个子元素开始往前计数

  • :nth-last-child(1),代表倒数第一个子元素

  • :nth-last-child(-n + 2),代表最后2个子元素

3. nth-of-type

:nth-of-type()  这个CSS 伪类是针对具有一组兄弟节点的标签, 用 n 来筛选出在一组兄弟节点的位置。

:nth-of-type()用法跟:nth-child()类似

  • 不同点是:nth-of-type()计数时只计算同种类型的元素
/* 需求: 选择box中的div元素, 并且是第三个子元素 */
.box > div:nth-child(3) {
  color: red;
}

/* 需求: 选择box中的第三个div元素(排除所有的干扰项) */
/* 元素:nth-of-type, 只计算符合我元素类型的数量的元素 */
.box > div:nth-of-type(3) {
  color: blue;
}

4. nth-last-of-type

:nth-last-of-type()用法跟:nth-of-type()类似

  • 不同点是:nth-last-of-type()从最后一个这种类型的子元素开始往前计数

3. 其他结构伪类

  • :first-child,等同于:nth-child(1)

  • :last-child,等同于:nth-last-child(1)

  • :first-of-type,等同于:nth-of-type(1)

  • :last-of-type,等同于:nth-last-of-type(1)

  • :only-child,是父元素中唯一的子元素

  • :only-of-type,是父元素中唯一的这种类型的子元素

下面的伪类偶尔会使用:

  • :root,根元素,就是HTML元素

  • :empty, 代表里面完全空白的元素

4. 否定伪类

  • :not()的格式是:not(x)

    • x是一个简单选择器

    • 元素选择器、通用选择器、属性选择器、类选择器、id选择器、伪类(除否定伪类)

  • :not(x)表示除x以外的元素

    .box :not(.abc) {
      color: blue;
    }