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

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

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

:where(selector1, selector2, selector3, ...) {
  /* 样式规则 */
}
  1. 零特异性(Zero Specificity)
    这是 where() 最重要的特性。它自身不会增加选择器的特异性权重。

  2. 简化复杂选择器
    可以帮助简化嵌套较深的选择器。

/* 传统写法 */
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
/* 基础样式 - 易于覆盖 */
:where(.card, .panel, .widget) {
  padding: 1rem;
  border: 1px solid #ccc;
}

/* 可以轻松覆盖 */
.card {
  padding: 2rem; /* 这个样式会生效 */
}
/* 使用 :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;
}
/* 组件基础样式(易于覆盖) */
.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; /* 这个会生效 */
}
/* 移动端优化 */
@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.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网开三面

你的鼓励将是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值