CSS3 新增伪类

CSS3 新增的结构性伪类、UI 状态伪类及使用示例

问题

CSS3 新增了哪些伪类?

解答

结构性伪类

/* 第一个/最后一个子元素 */
li:first-child { color: red; }
li:last-child { color: blue; }

/* 第 n 个子元素 */
li:nth-child(2) { color: green; }        /* 第 2 个 */
li:nth-child(odd) { background: #eee; }  /* 奇数行 */
li:nth-child(even) { background: #fff; } /* 偶数行 */
li:nth-child(3n) { font-weight: bold; }  /* 每隔 3 个 */

/* 从后往前数第 n 个 */
li:nth-last-child(2) { color: orange; }

/* 同类型元素中的第 n 个 */
p:nth-of-type(2) { color: purple; }
p:first-of-type { font-size: 20px; }
p:last-of-type { font-size: 14px; }

/* 唯一子元素 */
p:only-child { color: red; }    /* 父元素只有这一个子元素 */
p:only-of-type { color: blue; } /* 父元素只有这一个 p 元素 */

/* 空元素 */
div:empty { display: none; }

/* 根元素 */
:root { --main-color: #333; }

UI 状态伪类

/* 表单状态 */
input:enabled { background: white; }
input:disabled { background: #ccc; }
input:checked + label { color: green; }

/* 表单验证 */
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:required { border-left: 3px solid red; }
input:optional { border-left: 3px solid gray; }

/* 只读状态 */
input:read-only { background: #f5f5f5; }
input:read-write { background: white; }

/* 范围验证 */
input:in-range { border-color: green; }
input:out-of-range { border-color: red; }

其他伪类

/* 目标伪类 - 匹配 URL 锚点指向的元素 */
:target { background: yellow; }

/* 否定伪类 */
li:not(.active) { opacity: 0.5; }
input:not([disabled]) { cursor: pointer; }

/* 语言伪类 */
p:lang(zh) { font-family: "Microsoft YaHei"; }
p:lang(en) { font-family: Arial; }

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 表格斑马纹 */
    tr:nth-child(odd) { background: #f9f9f9; }
    tr:nth-child(even) { background: #fff; }
    
    /* 表单验证样式 */
    input:valid { border: 2px solid green; }
    input:invalid { border: 2px solid red; }
    
    /* 排除特定元素 */
    li:not(:last-child) { border-bottom: 1px solid #eee; }
  </style>
</head>
<body>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
  
  <input type="email" required placeholder="输入邮箱">
</body>
</html>

关键点

  • :nth-child(n) 从 1 开始计数,支持 oddevenan+b 表达式
  • :nth-child 计算所有子元素,:nth-of-type 只计算同类型元素
  • :not() 括号内只能放简单选择器,不能嵌套
  • UI 伪类配合 HTML5 表单验证使用效果更好
  • :target 常用于实现纯 CSS 的 Tab 切换或锚点高亮