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.

相关推荐
小雨下雨的雨1 小时前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
ZC跨境爬虫5 小时前
跟着 MDN 学JavaScript day_7:数学运算与逻辑判断实战测试
开发语言·前端·javascript·学习·ecmascript
fangdengfu1235 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
JustHappy6 小时前
古法编程秘籍(六):程序到底是怎么跑起来的?从 IO 到中断,一次讲明白
前端·后端·全栈
HYCS7 小时前
用pixi.js实现fabric.js(六):从线性代数的角度理解编辑器交互
前端·javascript·canvas
卷帘依旧7 小时前
useImperativeHandle的作用
前端
卷帘依旧7 小时前
Hooks在Fiber上的存储原理
前端
you45807 小时前
学成在线--day02 CMS前端开发(含Vue基础知识得回顾)
前端·javascript·vue.js
xiaofeichaichai7 小时前
虚拟 DOM
前端·javascript·vue.js