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.

相关推荐
phltxy2 分钟前
Vue3入门指南:从环境搭建到数据响应式,开启高效前端开发之旅
前端·javascript·vue.js
小飞大王6663 分钟前
CSS基础知识
前端·css
Charlie_lll6 分钟前
学习Three.js–风车星系
前端·three.js
代码游侠6 分钟前
学习笔记——Linux内核与嵌入式开发1
linux·运维·前端·arm开发·单片机·嵌入式硬件·学习
玩电脑的辣条哥23 分钟前
幽灵回复AI已回复但前端不显示的排查与修复
前端·人工智能
石去皿36 分钟前
轻量级 Web 应用 —— 把一堆图片按指定频率直接拼成视频,零特效、零依赖、零命令行
前端·音视频
星夜落月1 小时前
Web-Check部署全攻略:打造个人网站监控与分析中心
运维·前端·网络
冰暮流星1 小时前
javascript之双重循环
开发语言·前端·javascript
爱敲点代码的小哥1 小时前
C#视觉模板匹配与动态绘制实战(绘制和保存,加载tb块,处理vpp脚本的方式)
前端·javascript·信息可视化
南风知我意9572 小时前
【前端面试3】初中级难度
前端·javascript·面试