有没有办法降低CSS的特异性?

时间:2019-09-21 07:07:06

标签: css css-selectors css-specificity

我有一个CSS模板,我想在其中使用一些HTML标记中的最少属性,同时允许以后根据需要通过类(非ID)轻松定制该标记。< / p>

<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>

vs

<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是分配的最低内部特异性,依此类推。

还是我只是被迫在各处使用类?

2 个答案:

答案 0 :(得分:1)

  

有没有一种方法可以在不使用!important的情况下强制产生特异性? ...或@specify('[data-role="a"] > :last-of-type' , 10) { ... },其中10是指定的最低内部特异性

不,没有。

不确定您从答案中还在寻找什么,因为您似乎了解了一般的工作原理-仅使用那里提供的小型HTML,您至少可以用数十种方法来编写涉及元素,类,属性的规则等等以获得所需的样式。尽管如果您正在寻找简单,写得很好的关于特异性的文章,我总是发现这是最有用的:

https://css-tricks.com/specifics-on-css-specificity/(自2010年以来不断更新!)

答案 1 :(得分:1)

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

相关问题