:is() 和 :where() 可简化表单选择器,前者取最高优先级,后者权重为0;[type]含连字符值必须加引号;:checked不匹配indeterminate状态,需用:indeterminate并JS设置;:disabled不覆盖fieldset[disabled]子元素,应使用属性选择器。

用 :is() 和 :where() 简化表单选择器组合
现代 CSS 中,:is() 是匹配多种表单控件最干净的方式。比如要统一设置所有可输入控件的边框和字体,不用重复写 input、textarea、select、button 四遍,直接:
:is(input, textarea, select, button) {
border: 1px solid #ccc;
font-family: system-ui, sans-serif;
}注意::is() 会取括号内选择器的最高优先级(比如 input[type="text"] 和 textarea 混用时,整体权重按前者算),而 :where() 权重恒为 0 —— 如果你只想覆盖默认样式又不想被其他规则压住,用 :where() 更安全。
[type] 属性选择器必须加引号才能匹配带连字符的值
写 input[type=number] 没问题,但写 input[type=datetime-local] 会失效 —— 浏览器会把它解析成「input[type=datetime」加一个非法的伪类 -local。正确写法是加引号:input[type="datetime-local"]。同理适用于 "color"、"week"、"search" 等所有含连字符的 type 值。不加引号不是“有时能用”,而是根本不会命中目标元素。
区分 :checked 和 :indeterminate 的实际触发条件
:checked 只对 和 生效,且仅当用户主动勾选或 JS 设置 .checked = true 时才匹配。它**不会**匹配 indeterminate 状态(即“半选”状态)。这个状态必须用 :indeterminate 单独捕获,而且只能通过 JS 设置:
const cb = document.querySelector('input[type="checkbox"]');
cb.indeterminate = true; // 此时 :indeterminate 才生效,:checked 不匹配注意:原生 或 组没有自动 indeterminate 行为,得手动控制。
禁用表单控件的样式穿透陷阱
:disabled 能匹配所有禁用控件,但容易忽略两点:
- 它不匹配
fieldset[disabled]下的子控件 —— 那些控件虽不可交互,但 DOM 上没设disabled属性,所以input:disabled不会选中它们 -
fieldset[disabled]自身样式不会自动继承到子元素,必须显式写fieldset[disabled] input或fieldset[disabled] :is(input, select)
fieldset[disabled] 内的 button 不触发 :disabled 伪类,稳妥做法是统一用属性选择器:input[disabled], select[disabled], button[disabled], fieldset[disabled] *。










