:not()仅接受简单选择器,禁用复合选择器与伪元素;合法如:not(.active)、:not([disabled]);多条件需嵌套;不可否定:has()等受限伪类;配合:is()/:where()提升可读性与兼容性。

伪类 :not() 的基本写法和限制
:not() 只接受「简单选择器」作为参数,不能写复合选择器或后代关系。比如 :not(.btn:hover)、:not(div p) 都是非法的,浏览器会直接忽略整条规则。
合法写法包括::not(.active)、:not([disabled])、:not(:first-child)、:not(input[type="text"])(注意:属性选择器算简单选择器)。
- 多个条件要嵌套使用,例如排除既有
.error又有.hidden的元素?不行 ——:not(.error.hidden)是合法的(这是单个选择器),但:not(.error):not(.hidden)才是真正“排除任一满足”的逻辑 -
:not()无法否定伪元素(如:not(::before))或某些伪类(如:not(:has(...))在部分浏览器仍受限)
用 :not() 排除带特定属性或状态的表单控件
常见需求:给所有 input 加边框,但跳过 type="hidden" 和已禁用的。
input:not([type="hidden"]):not(:disabled) {
border: 1px solid #ccc;
}注意顺序不影响逻辑结果,但建议把更具体的筛选放前面(如先筛 [type] 再筛状态),便于阅读;另外 :disabled 对 input、button、select 等有效,但对 div[disabled] 无效 —— 属性存在不等于语义生效。
立即学习“前端免费学习笔记(深入)”;
-
input:not([type="submit"]):not([type="reset"])可用于样式化普通输入框,避开按钮类控件 - 想排除
readonly但保留disabled?得写input:not(:read-only):not(:disabled),因为:read-only是独立伪类,[readonly]属性选择器不等价(比如 JS 动态设el.readOnly = true不会添加属性)
配合 :is() 或 :where() 提升可读性与兼容性
当需要排除多种标签或复杂条件时,单独堆砌 :not() 易出错。例如「所有标题但排除 h1 和 h2」:
h1, h2, h3, h4, h5, h6:not(h1):not(h2) { /* ❌ 错误:h1/h2 自身也会被前面的选择器匹配 */ }正确做法是统一用 :is() 包裹主体,再在外层 :not():
:is(h3, h4, h5, h6) {
margin-top: 1rem;
}如果真要「选所有标题,除了 h1 和 h2」,得写成:
:is(h1, h2, h3, h4, h5, h6):not(:is(h1, h2)) { ... }-
:where()优先级为 0,适合做兜底排除(比如重置某类元素样式时不想提高权重) - 旧版浏览器不支持
:is(),此时只能拆成多条规则,或用 BEM 类名规避深层逻辑
容易被忽略的层叠与作用域陷阱
:not() 不改变选择器权重,但会影响匹配结果是否进入后续层叠流程。例如:
.card > *:not(.card-header) { color: #333; }
.card-header { color: #fff; }看起来没问题,但如果 .card-header 同时有 .highlight 类,而你写了 .highlight { color: red !important; },那它依然会被 :not(.card-header) 排除 —— 因为 :not() 判断的是元素是否带有该类,不是判断最终渲染效果。
- 动态添加/移除 class 时,
:not()实时响应,但不要依赖它做“条件渲染替代”,JS 控制显隐更可控 - 在 Shadow DOM 中,
:not()只作用于当前作用域,无法跨影子边界匹配 - 伪类组合如
:not(:hover):not(:focus)在键盘操作中可能意外触发,测试时需覆盖 tab 导航路径










