---
title: CSS is() 与 where() 选择器:简化匹配与权重治理
keywords:
- :is()
- :where()
- 选择器权重
- 简化匹配
- 可维护性
description: 使用 :is()/:where() 简化复杂选择器匹配,并通过 :where() 的零权重特性治理覆盖与级联,提升样式可维护性。
categories:
- 文章资讯
- 编程技术
---
概述
:is() 将多种选择器合并为一个,使用最高权重参与级联;:where() 行为类似但不增加权重(特性为零),适合在架构中用于包裹前缀与容器类以避免权重膨胀。
用法/示例
/* :is 合并多选择器 */
.menu :is(a, button, [role="link"]) { color: #111 }
/* :where 不增加权重,用于容器作用域 */
:where(.card) :is(.title, h2) { font-weight: 600 }
/* 结合状态 */
.list :is(li:hover, li:focus-visible) { background: #f3f4f6 }
工程建议
- 用
:where()包裹组件根或容器类,控制权重并减少!important的需求。 - 将复杂匹配合并到
:is(),避免重复选择器;保留清晰的作用域与层次。 - 在旧浏览器提供降级选择器或通过构建时转译处理。
参考与验证
- MDN:
:is()— https://developer.mozilla.org/docs/Web/CSS/:is - MDN:
:where()— https://developer.mozilla.org/docs/Web/CSS/:where - Selectors Level 4 — https://www.w3.org/TR/selectors-4/

发表评论 取消回复