css使用 :where() 来简化大型 CSS 选择器列表

使用 :where() 来简化大型 CSS 选择器列表

where() 是 CSS 中的一个非常有用的伪类函数,它属于 CSS Selectors Level 4 规范

css 复制代码
:where(selector1, selector2, selector3, ...) {
  /* 样式规则 */
}
  1. 零特异性(Zero Specificity)

    这是 where() 最重要的特性。它自身不会增加选择器的特异性权重。

  2. 简化复杂选择器

    可以帮助简化嵌套较深的选择器。

css 复制代码
/* 传统写法 */
nav ul li a,
aside ul li a,
footer ul li a {
  color: #333;
}

/* 使用 :where() */
:where(nav, aside, footer) ul li a {
  color: #333;
}
  1. 易于覆盖样式
    由于零特异性,使用 :where() 的样式很容易被覆盖。
css 复制代码
css
/* 基础样式 - 易于覆盖 */
:where(.card, .panel, .widget) {
  padding: 1rem;
  border: 1px solid #ccc;
}

/* 可以轻松覆盖 */
.card {
  padding: 2rem; /* 这个样式会生效 */
}
css 复制代码
/* 使用 :where 重置多个容器的内部元素间距 */
:where(.post, .sidebar, .card) :where(h1, h2, h3, h4, h5, h6) {
  margin-top: 0;
  margin-bottom: 0.5em;
}

:where(.post, .sidebar, .card) :where(ul, ol) {
  padding-left: 1.5em;
}

:where(.post, .sidebar, .card) :where(p) {
  line-height: 1.6;
  margin-bottom: 1em;
}
css 复制代码
/* 组件基础样式(易于覆盖) */
.my-component :where(.title, .heading) {
  font-size: 1.2rem;
  margin-bottom: 1rem;
}

.my-component :where(.button, .btn) {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
}

/* 用户可以轻松自定义 */
.my-component .title {
  font-size: 1.5rem; /* 这个会生效 */
}
css 复制代码
/* 移动端优化 */
@media (max-width: 768px) {
  :where(nav, header, footer) {
    padding: 0.5rem;
  }
  
  :where(.card, .article, .sidebar) {
    margin-bottom: 1rem;
  }
}

当您需要编写基础样式、重置样式或希望样式容易被覆盖时,:where() 是最佳选择。
See the Pen css`:where()` by liu874396180 ( @liu874396180) on CodePen.

相关推荐
凯瑟琳.奥古斯特14 分钟前
Bootstrap快速上手指南
开发语言·前端·css·bootstrap·html
精益数智工坊19 分钟前
拆解制造业仓库物料管理流程:如何通过标准化仓库物料管理流程解决账实不符难题
大数据·前端·数据库·人工智能·精益工程
恶猫23 分钟前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
小羊Yveesss42 分钟前
2026年前端开发新趋势:智能协同、工具革新与场景深耕
前端·ai
Dxy12393102161 小时前
HTML中的Canvas可以干哪些事情
前端·html
悟乙己1 小时前
解析 Agent 时代的 HTML PPT SKILLS: html-ppt-skill
前端·html·powerpoint
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_2:(表单分组与高级输入控件实战)
前端·javascript·css·ui·html
ppandss12 小时前
JavaWeb从0到1-DAY4-AJAX
前端·ajax·okhttp
涵涵(互关)2 小时前
语法大全-only-writer-two
前端·vue.js·typescript
huangql5202 小时前
浏览器 Location API、History API、路由记录与支付跳转完全指南
前端