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 的"选择器助手",让你的样式更简洁、更可维护,合理利用权重差异,还能轻松写出优雅的架构。

相关推荐
奶球不是球16 小时前
elementplus组件中el-calendar组件自定义日期单元格内容及样式
javascript·css·css3
我这一生如履薄冰~18 小时前
css属性pointer-events: none
前端·css
苏打水com21 小时前
第十九篇:Day55-57 前端工程化进阶——从“手动低效”到“工程化高效”(对标职场“规模化”需求)
前端·css·vue·html
kirinlau1 天前
vue3+vite+scss项目使用tailwindcss
前端·css·scss
composurext1 天前
录音切片上传
前端·javascript·css
狮子座的男孩1 天前
html+css基础:07、css2的复合选择器_伪类选择器(概念、动态伪类、结构伪类(核心)、否定伪类、UI伪类、目标伪类、语言伪类)及伪元素选择器
前端·css·经验分享·html·伪类选择器·伪元素选择器·结构伪类
小白阿龙1 天前
样式不生效/被覆盖(CSS优先级陷阱)
前端·css
elangyipi1231 天前
cursor: not-allowed 与 pointer-events: none 深度解析
css
七月十二1 天前
类似渐变色弯曲border
css
ttod_qzstudio1 天前
Vue 3 的魔法:用 v-bind() 让 CSS 爱上 TypeScript 常量
css·vue.js·typescript