CSS 伪类是添加到选择器的关键字,用于指定所选元素的特殊状态。本文档提供了 CSS 伪类的完整参考。
/* 常用伪类示例 */
a:hover { text-decoration: underline; }
button:active { transform: translateY(1px); }
input:focus { border-color: blue; }
a:link { color: blue; }
a:visited { color: purple; }
#section:target { background-color: #ffffd0; }
/* 结构性伪类示例 */
li:first-child { font-weight: bold; }
tr:nth-child(even) { background-color: #f2f2f2; }
tr:nth-child(odd) { background-color: #ffffff; }
p:last-child { margin-bottom: 0; }
:root { --main-color: #06c; }
div:empty { display: none; }
p:nth-of-type(3n+1) { margin-top: 2em; }
/* 表单相关伪类示例 */
input:required { border-left: 4px solid red; }
input:valid { border-left: 4px solid green; }
input:invalid { background-color: #fff0f0; }
input:disabled { opacity: 0.5; }
input:checked + label { font-weight: bold; }
input:in-range { border-color: green; }
input:out-of-range { border-color: red; }
input:placeholder-shown { background-color: #f8f8f8; }
/* 逻辑组合伪类示例 */
div:not(.special) { background-color: #f0f0f0; }
:is(h1, h2, h3):hover { color: #06c; }
:where(article, section) p { line-height: 1.6; }
div:has(> img) { padding: 10px; }
/* 语言和方向性伪类示例 */
p:lang(zh) { font-family: "SimSun", serif; }
p:dir(rtl) { text-align: right; }
伪类可以组合使用,创建更精确的选择器:
/* 选择被禁用且必填的输入框 */
input:disabled:required {
border: 1px dashed red;
}
/* 选择鼠标悬停在非禁用按钮上时 */
button:not(:disabled):hover {
background-color: #0056b3;
}
/* 选择第一个且是唯一子元素的段落 */
p:first-child:only-child {
font-size: 1.2em;
}
这些伪类接受形式为 an+b
的参数,其中:
/* 选择每第三个元素 */
li:nth-child(3n) { background-color: #f0f0f0; }
/* 选择第一个和每隔4个元素 */
li:nth-child(4n+1) { font-weight: bold; }
/* 选择前三个元素 */
li:nth-child(-n+3) { border-bottom: 1px solid #ddd; }
/* 选择最后三个元素 */
li:nth-last-child(-n+3) { border-top: 1px solid #ddd; }
大多数常用伪类在现代浏览器中都得到良好支持。以下是一些需要注意的兼容性问题:
伪类 | Chrome | Firefox | Safari | Edge | IE |
---|
基本伪类(:hover, :active, :focus) | 完全支持 | 完全支持 | 完全支持 | 完全支持 | 8+ |
结构性伪类(:nth-child, :first-of-type) | 完全支持 | 完全支持 | 完全支持 | 完全支持 | 9+ |
:focus-visible | 86+ | 85+ | 15.4+ | 86+ | 不支持 |
:focus-within | 60+ | 52+ | 10.1+ | 79+ | 不支持 |
:is() | 88+ | 78+ | 14+ | 88+ | 不支持 |
:where() | 88+ | 78+ | 14+ | 88+ | 不支持 |
:has() | 105+ | 121+ | 15.4+ | 105+ | 不支持 |