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.

相关推荐
泷羽Sec-静安3 小时前
Less-9 GET-Blind-Time based-Single Quotes
服务器·前端·数据库·sql·web安全·less
pe7er3 小时前
用高阶函数实现递归:从匿名函数到通用递归生成器
前端·javascript
IT古董3 小时前
全面理解 Corepack:Node.js 的包管理新时代
前端·node.js·corepack
学习3人组3 小时前
清晰地说明 NVM、NPM 和 NRM 在 Node.js 开发过程中的作用
前端·npm·node.js
矢心3 小时前
setTimeout 和 setInterval:看似简单,但你不知道的使用误区
前端·javascript·面试
一枚前端小能手3 小时前
🧭 使用历史记录 API - SPA导航与状态管理的完整指南
前端·javascript
用户47949283569153 小时前
从字符串满天飞到优雅枚举:JavaScript 常量管理的几种姿势
前端·javascript
qq_415216254 小时前
Vue3+vant4+Webpack+yarn项目创建+vant4使用注意明细
前端·webpack·node.js
李建军4 小时前
ASP.NET Core Web 应用SQLite数据连接显示(1)
前端
耀耀切克闹灬4 小时前
word文档转html(mammoth )
前端