在 CSS 中,你可以使用 :not() 伪类选择器来排除特定的类名、ID 或其他元素。以下是几种常见的排除方法:
- 排除某个类名
/* 选择所有 ul,但不包括 .single-meta 类 */
ul:not(.single-meta) {
font-size: 14px;
}
- 排除某个 ID
/* 选择所有 div,但不包括 #sidebar */
div:not(#sidebar) {
margin: 0;
}
- 排除多个类或 ID
/* 选择所有 p,但不包括 .note 和 .warning 类 */
p:not(.note):not(.warning) {
color: #333;
}
/* 选择所有 a,但不包括 #external-link 和 .disabled */
a:not(#external-link):not(.disabled) {
text-decoration: none;
}
- 结合其他选择器
/* 选择 .content 下的 ul,但不包括 .no-style */
.content ul:not(.no-style) {
list-style: none;
padding-left: 0;
}
- 排除特定属性
/* 选择所有 input,但不包括 type="submit" */
input:not([type="submit"]) {
border: 1px solid #ccc;
}
注意事项
:not() 只能接受简单选择器(不能嵌套 :not() 或使用复杂选择器):
/* 错误写法(不支持) */
ul:not(.class1.class2) { ... }
/* 正确写法 */
ul:not(.class1):not(.class2) { ... }
兼容性:现代浏览器都支持 :not(),但在极旧浏览器(如 IE8 及以下)可能不生效。
性能优化
过度使用 :not() 可能影响渲染性能,尽量保持选择器简洁。示例:排除 .single-meta 的无序列表样式
/* 选择 .content-single 下的 ul,但不包括 .single-meta */
.content-single ul:not(.single-meta) {
font-size: 14px;
list-style: none;
padding-left: 1.5em;
}
/* 自定义列表标记 */
.content-single ul:not(.single-meta) li::before {
content: "•";
color: #4a90e2;
margin-right: 0.5em;
}
这样,.single-meta 类的 ul 就不会应用这些样式。