【问题标题】:css :pseudo-class for increasing the specificitycss:用于增加特异性的伪类
【发布时间】:2022-01-14 09:28:48
【问题描述】:

是否有一个伪类具有最少字符,几乎总是匹配任何东西?

现在我正在使用nth-child(n),但我不太高兴,因为字符太多。 或者使用真正的类:not(._)。

你能建议我更好的选择吗?

我想用它来增加特异性。插图如下:

/* the specificity index is [0,5,0] */
:nth-first-child(2n+3):nth-child(n):nth-child(n):nth-child(n):nth-child(n) {
   color: 'red',
}

注意:

  • 不要使用!important,因为该规则太难以后被覆盖。
  • 不要使用 #idfoo,因为 id 特异性比(伪)类或 attr 选择器大一个数量级,因此很难被覆盖。

我为什么要这样做? 因为我正在制作一个 CSS 库,一些 state classes 像 .enabled, .active, .engaged, .excited 必须比 variant classes 更占主导地位.big、.dark、.mini。 以后应该可以轻松地覆盖所有主要和非主要类。

【问题讨论】:

  • 这个的用例是什么?我本能地感到恐惧,因为这听起来像是让代码变得难以阅读的好方法。
  • 人为地增加特异性几乎和使用 !important 一样糟糕。您应该查看您真正想要定位的元素,并仅覆盖这些元素已经存在的规则。
  • 我想定义一个覆盖其他选择器但仍然可以被另一个子子组件覆盖的选择器
  • 我在 javascript 中创建了一个css builder,如下所示:defineRule([':disabled', '.enabled', '.excited'], { color: 'black' }, { minSpecificity: 3 }) 然后呈现给:is(:disabled, :enabled, .excited):nth-child(n):nth-child(n)

标签: css css-specificity


【解决方案1】:

使用:not(#_)。 ID 选择器强于类或:nth-child()

h1:not(#_) {
  color:blue;
}

h1.title {
  color:red;
}
<h1 class="title">text</h1>

【讨论】:

  • id 选择器更强,但在子子组件上很难重新覆盖。我正在制作一个允许进一步覆盖的 css 库。
猜你喜欢
  • 2012-07-19
  • 2016-05-04
  • 2020-04-09
  • 2014-07-11
  • 1970-01-01
  • 2013-03-30
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多