CSS `:is()` & `:where()` 实战指南:简化选择器,提升可维护性

发布于:2025-09-14 ⋅ 阅读:(26) ⋅ 点赞:(0)

🎯 CSS :is() & :where() 实战指南:简化选择器,提升可维护性

你是否在项目中写过一大串重复的选择器?比如:

h1, h2, h3, h4, h5, h6 { margin-bottom: 1rem; }

这样的代码既冗长又难维护。
现在 CSS 提供了 :is():where() 选择器,让你可以写得更短、更优雅,还能更好地控制优先级。


🧠 什么是 :is():where()

它们都是 选择器列表函数,允许你在一个规则中传入多个候选选择器:

  • :is():匹配多个选择器,计算 正常的优先级
  • :where():匹配多个选择器,但 权重始终为 0

✅ 基础示例

/* 用 :is() 简化 */
:is(h1, h2, h3, h4, h5, h6) {
  margin-bottom: 1rem;
}

效果等同于:

h1, h2, h3, h4, h5, h6 {
  margin-bottom: 1rem;
}

🧪 实战一:按钮多状态写法

.button:is(:hover, :focus, :active) {
  background: #4f46e5;
  color: white;
}

📌 优势:不再写 .button:hover, .button:focus, .button:active,简洁很多。


🧪 实战二:用 :where() 降低选择器优先级

/* 全局 reset 样式 */
:where(h1, h2, h3, p) {
  margin: 0;
  padding: 0;
}

📌 因为 :where() 权重为 0,后续样式可以轻松覆盖,不会“打架”。


🌟 高级技巧

  1. 组合选择器

    .card :is(h2, h3) {
      color: #111;
    }
    

    ✅ 匹配 .card 内的所有 h2h3

  2. 与伪类结合

    nav :is(a:hover, a:focus) {
      text-decoration: underline;
    }
    
  3. 重置 + 覆盖最佳实践

    • :where() 写 Reset(低优先级)
    • :is() 写组件逻辑(正常优先级)

🌐 浏览器支持(2025)

浏览器 支持情况
Chrome 88+
Safari 15+
Firefox 78+
Edge 88+

📌 几乎已完全普及,可以放心用在生产环境。


⚠️ 注意事项

  • :is() 的权重 = 里面最具体选择器的权重

    div:is(.highlight, #id) { ... }
    

    权重会按 #id 来算。

  • :where() 永远是 0 权重,适合写 Reset 或全局初始化。

  • 不要滥用,否则可读性可能下降。


✨ 一句话总结

:is():where() 是现代 CSS 的“选择器助手”,让你的样式更简洁、更可维护,合理利用权重差异,还能轻松写出优雅的架构。