css - 有没有办法强制降低 CSS 的特异性?

标签 css css-selectors css-specificity

我有一个 CSS 模板,我想在某些 HTML 标记中使用最少量的属性,同时允许在以后需要时通过类 (不是 ID) 轻松自定义该标记。

<ul data-role = 'a'>
  <li>A</li>
  <li>B</li>
</ul>
<style>
  [data-role="a"] { /* ... */ }
  [data-role="a"] > :first-of-type { /* ... */ }
  [data-role="a"] > :last-of-type { /* ... */ }
</style>

问题是,由于 CSS 的特殊性,我面临着要么创建所有选择器类,要么强制对我的内容进行的任何样式表修改都非常具体:

<style>
[data-role="a"] > li { } /* custom overriding CSS */
</style>

对比

<ul class = 'a'>
  <li class = 'a-top'>A</li>
  <li class = 'a-bottom'>B</li>
</ul>
<style>
  a {/* */}
  a-top {/* */}
  a-bottom {/* */}
</style>

有没有办法在不使用 !important 的情况下强制产生特异性,例如假设:

@yield to classes {
  [data-role = "a"] { } 
  [data-role = "a"] > :first-of-type { }
  [data-role = "a"] > :last-of-type { }
  /* etc */
}

@specify('[data-role="a"] > :last-of-type' , 10) { ... } 其中 10 是分配的最低内部特异性等。

还是我只是被迫到处使用类?

最佳答案

MDN 有一个有趣的提示,可以帮助您在不使用 !important 的情况下摆脱困境: 使用一个选择器两次:

#myId#myId span { color: yellow; }
.myClass.myClass span { color: orange; }

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

最近对 :where() 伪类的支持被添加到主要浏览器中。它允许更好地管理特异性。内部的选择器不影响整体选择器的特异性:

:where(aside.where, footer.where) a {
  color: orange;
}

footer a {
  color: blue;
}
<aside class="where">
  <p>Here is my aside content. This <a href="https://developer.mozilla.org">also contains a link</a>.
</aside>

<footer class="where">
  <p>This is my footer, also containing <a href="https://github.com/mdn">a link</a>.
</footer>

https://developer.mozilla.org/en-US/docs/Web/CSS/:where

进一步注意,根据an approach called BEM (Block, Element, Modifier)无论如何,使用类(任何元素一个类)可能不是最糟糕的选择。

关于css - 有没有办法强制降低 CSS 的特异性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038056/

相关文章:

jquery - 甚至 tr 的 LESS (CSS) 选择器,没有 class .hide

CSS:将复选框设置为看起来像按钮的样式,是否有悬停?

css - 来自兄弟父 div 的子选择器使用 css 实现悬停效果

css - CSS 中宽度 :100%! important 和高度 :100%! important 有什么用?

伪类和伪元素在特异性计算中的 CSS 区别?

html - 我如何为 div 中的链接添加不同的样式并向其添加类?

html - 问题让 Div 靠近另一个拥抱

html - html 页面的右边距与左边距不同

html - 突出显示相同的第 n 个子元素

html - CSS 滑出式菜单