Reference CSS reference

CSS :has() 参考

:has() 是关系伪类,可以根据内部元素或后续元素状态匹配当前元素。它常被称为“父选择器”,但也可以表达更广的关系条件。

语法

css
.field:has(input:invalid) {
  border-color: #dc2626;
}

常见用法

css
article:has(img) {
  display: grid;
}

form:has(:invalid) button[type="submit"] {
  opacity: 0.6;
}

可运行演示

在线代码演示
源码
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>:has 表单状态演示</title>
    <style>
      body { margin: 0; padding: 24px; font-family: system-ui, sans-serif; background: #f8fafc; color: #0f172a; }
      .field { max-width: 520px; margin: 0 auto; padding: 16px; border: 1px solid #dbeafe; border-radius: 12px; background: #fff; }
      label { display: grid; gap: 8px; font-weight: 600; }
      input { padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; font: inherit; }
      .hint { color: #64748b; }
      .field:has(input:invalid) { border-color: #fca5a5; background: #fff7f7; }
      .field:has(input:valid) .hint { color: #15803d; }
    </style>
  </head>
  <body>
    <div class="field">
      <label>邮箱 <input type="email" required value="[email protected]"></label>
      <p class="hint">输入合法邮箱后,提示文字会变绿。</p>
    </div>
  </body>
</html>

常见错误

  • 选择器写得过宽,导致样式影响大量父级元素。
  • 用 :has() 做复杂状态管理,后期维护困难;复杂交互仍应交给 JavaScript。
  • 忽略浏览器兼容性和性能,尤其是在大范围 DOM 上使用复杂选择器。

相关内容