CSS 伪类参考手册
CSS 伪类
伪类用于定义元素的特殊状态。
例如,它可以用于:
- 当用户将鼠标悬停在元素上时设置样式
- 为已访问和未访问的链接设置不同的样式
- 当元素获得焦点时设置样式
- 为有效/无效/必填/选填的表单元素设置样式
下表展示了 CSS 中不同的伪类:
| 伪类 | 例子 | 例子描述 |
|---|---|---|
:active |
a:active |
选择活动链接 |
:any-link |
a:anylink |
选择所有带有 href 属性的 <a> 或 <area> 元素。 |
:auto-fill |
input:autofill |
选择所有由浏览器自动填充值的 <input> 元素。 |
:checked |
option:checked |
匹配所有被选中的 <input> 或 <option> 元素。 |
:default |
input:default |
选择一组相关元素中的默认表单元素。 |
:defined |
:defined |
选择所有已定义的元素(标准或自定义元素)。 |
:dir() |
:dir(rtl) |
选择具有指定文本方向的元素。 |
:disabled |
option:disabled |
选择所有被禁用的元素,常用于表单元素。 |
:empty |
div:empty |
选择所有没有子元素(包括文本节点)的元素。 |
:enabled |
input:enabled |
选择所有启用的元素,常用于表单元素。 |
:first |
@page :first |
表示打印文档的第一页(与 @page 规则一起使用)。 |
:first-child |
p:first-child |
选择作为其父元素第一个子元素的元素(在一组兄弟元素中)。 |
:first-of-type |
li:first-of-type |
选择一组兄弟元素中第一个特定类型的元素。 |
:focus |
select:focus |
选择获得焦点的元素,常用于表单元素。 |
:focus-visible |
button:focus-visible |
选择获得焦点的元素(仅在通过键盘而非鼠标聚焦时应用焦点样式)。 |
:focus-within |
form:focus-within |
匹配元素或其任何后代获得焦点的元素。 |
:fullscreen |
:fullscreen |
选择当前处于全屏模式的元素。 |
:has() |
h2:has(+p) |
选择紧接在 <p> 元素后的 <h2> 元素,并将样式应用于 <h2>。 |
| :hover | a:hover | 选择鼠标悬停的元素。 |
:in-range |
input:in-range |
选择值在指定范围内的 <input> 元素。 |
:indeterminate |
input:indeterminate |
选择处于不确定状态的表单元素。 |
:invalid |
input:invalid |
选择无效的表单元素。 |
:is() |
:is(ul, ol) |
选择所有 <ul> 和 <ol> 元素。 |
:lang() |
p:lang(it) |
选择 lang 属性为 "it"(意大利语)的 <p> 元素。 |
:last-child |
li:last-child |
选择作为其父元素最后一个子元素的 <li> 元素。 |
:last-of-type |
p:last-of-type |
选择作为其父元素最后一个 <p> 元素的 <p> 元素。 |
:left |
@page :left |
表示打印文档的所有左侧页面(与 @page 规则一起使用)。 |
:link |
a:link |
选择所有未访问的链接。 |
:modal |
:modal |
选择处于模态状态的元素。 |
:not() |
:not(p) |
选择所有不是 <p> 元素的元素。 |
:nth-child() |
p:nth-child(2) |
选择作为其父元素第二个子元素的 <p> 元素。 |
:nth-last-child() |
p:nth-last-child(2) |
选择作为其父元素倒数第二个子元素的 <p> 元素。 |
:nth-last-of-type() |
p:nth-last-of-type(2) |
选择作为其父元素倒数第二个 <p> 元素的 <p> 元素。 |
:nth-of-type() |
p:nth-of-type(2) |
选择作为其父元素第二个 <p> 元素的 <p> 元素。 |
:only-child |
p:only-child |
选择作为其父元素唯一子元素的 <p> 元素。 |
:only-of-type |
p:only-of-type |
选择作为其父元素唯一 <p> 元素的 <p> 元素。 |
:optional |
textarea:optional |
选择没有 required 属性的 <input>、<select> 或 <textarea> 元素。 |
:out-of-range |
input:out-of-range |
选择值超出指定范围的 <input> 元素。 |
:placeholder-shown |
input:placeholder-shown |
选择当前显示占位符文本的 <input> 或 <textarea> 元素。 |
:popover-open |
:popover-open |
选择处于显示弹出状态的元素。 |
:read-only |
input:read-only |
选择带有 readonly 属性的输入元素。 |
:read-write |
input:read-write |
选择可编辑的输入元素。 |
:required |
input:required |
选择带有 required 属性的输入元素。 |
:right |
@page :right |
表示打印文档的所有右侧页面(与 @page 规则一起使用)。 |
:root |
:root |
选择文档的根元素。 |
:scope |
:scope |
选择作为选择器匹配参考点或范围的元素。 |
:state() |
:state() |
选择具有指定自定义状态的自定义元素。 |
:target |
:target |
选择当前活动的目标元素。 |
:user-invalid |
:user-invalid |
选择具有无效值的表单元素(在用户与其交互后)。 |
:user-valid |
:user-valid |
选择具有有效值的表单元素(在用户与其交互后)。 |
:valid |
input:valid |
选择所有具有有效值的输入元素。 |
:visited |
a:visited |
选择所有已访问的链接。 |
:where() |
:where(ol, ul) |
选择所有 <ul> 和 <ol> 元素。 |