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

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

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

css 复制代码
h1, h2, h3, h4, h5, h6 { margin-bottom: 1rem; }

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


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

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

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

✅ 基础示例

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

效果等同于:

css 复制代码
h1, h2, h3, h4, h5, h6 {
  margin-bottom: 1rem;
}

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

css 复制代码
.button:is(:hover, :focus, :active) {
  background: #4f46e5;
  color: white;
}

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


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

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

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


🌟 高级技巧

  1. 组合选择器

    css 复制代码
    .card :is(h2, h3) {
      color: #111;
    }

    ✅ 匹配 .card 内的所有 h2h3

  2. 与伪类结合

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

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

🌐 浏览器支持(2025)

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

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


⚠️ 注意事项

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

    css 复制代码
    div:is(.highlight, #id) { ... }

    权重会按 #id 来算。

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

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


✨ 一句话总结

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

相关推荐
爱吃甜品的糯米团子10 小时前
CSS Grid 网格布局完整指南:从容器到项目,实战详解
前端·css
web3d52013 小时前
CSS水平垂直居中终极指南:从入门到精通
前端·css
我有一棵树16 小时前
如何优雅的布局,height: 100% 的使用和 flex-grow: 1 的 min-height 陷阱
前端·css·html
m0_6161884916 小时前
CSS中的伪类和伪元素
前端·javascript·css
加油乐18 小时前
Sass与Less的特性与区别
前端·css
forever_Mamba1 天前
CSS隐藏页面元素
前端·css
β添砖java1 天前
CSS定位布局
前端·css·html
lyj1689971 天前
CSS中 min() max() clamp()函数
前端·javascript·css
用户458203153172 天前
CSS性能优化全攻略:提升页面加载与渲染速度
前端·css
立方世界2 天前
CSS水平垂直居中方法深度分析
前端·css