我有一个 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/