跳到主要内容

伪类

交互状态

  • ​​:hover

    鼠标在元素上悬停。

  • :active

    元素激活,比如按钮被按下。

  • :focus & :focus-within

    作用于可获取焦点的元素,比如按钮。:focus-within 允许后代元素的获取焦点。

  • :target

    当前网页 URL 与 HTML 中的某个 id 匹配时。

历史状态

  • :link 带有 href 属性的元素。

  • :visited 访问过的链接。

可用的属性有:color background-color border-color outline-color

在同优先级下 :visited 可能会被 :link 覆盖。所以建议按照如下顺序定义这些伪类:

:link -> :visited -> :hover -> :active(简称 LVHA )

表单状态

  • :disable & :enable 元素(比如按钮)的禁用和可用状态。

  • :checked 用于选框。

  • :indeterminate 用于非决定的状态(元素的 indeterminate 属性)。

  • :valid & :invalid

    <input type="email" required />
    input:invalid {
    border-color: red;
    }
  • :required & :optional

    表单中有 required 属性的元素可以用 :required ,非 required 元素则用 :optional

  • :in-range 用在一个有 minmaxinput 元素。比如滑动条

​​元素位置

  • :first-child:last-child:only-child

    当自己作为父元素的第一个,最后一个,唯一一个子元素时。

  • :first-of-type:last-of-typeonly-of-type

    当自己作为父元素的第一个、最后一个、唯一一个某种类型的子元素时。

  • nth-child()nth-of-type()

    可以用 odd、even 关键词,或者 An+B 表达式

  • :empty

    没有子元素

多类元素的选择

  • :is(...)​

    多种元素的选择。

    .post h2, .post li, .post img {
    /* … */
    }
    /* 可以写为:*/
    .post :is(h2, li, img) {
    /* … */
    }
  • :not(...)

    排除指定元素类型。


参考

Pseudo-classes,Learn CSS - web.dev