:nth-child

  • :nth-child (1): 是父元素中的第 1 个子元素
  • :nth-child (n): 所有子元素, n 可以取值 0, 1, 2, 3 …
  • :nth-child (2n): 父元素中的第偶数个子元素
    • 跟: nth-child (even) 同义
  • :nth-child (2n + 1): 父元素中的第奇数个子元素
    • 跟: nth-child (odd) 同义
  • :nth-child (-n + 2): 代表前 2 个子元素
<style>
ul li:nth-child(3) {
/*color: red;*/
font-size: 10px;
}

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

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

/*四个一组:橘色/紫色/红色/蓝色 */
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;
}

/* 前几个 */
div > div:nth-child(-n + 5) {
font-size: 20px;
}
</style>
---------------------------
<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>
------------------------------

:nth-last-child

与 :nth-child () 类似, :nth-last-child 是从后往前

:nth-of-type

:nth-child () 类似, :nth-of-type () 计数时只计算同种类型的元素

:nth-last-of-type

与 :nth-of-type () 类似, 是从后往前

:not

格式是 :not (x), 表示除 x 以外的元素

  • x 是一个简单选择器
  • 元素选择器、通用选择器、属性选择器、类选择器、 id 选择器、伪类(除否定伪类)

其他常见的伪类

  • :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 代表里面完全空白的元素