一个 CSS 优先级的问题

2021-11-20 16:57:14 +08:00
 WhateverYouLike

代码是这样的

*,*::before,*::after{	font-family: "A";}
[class^=icon-], [class*=" icon-"] {  font-family: "B" !important;}
.icon-search::before{ content: ""}
<span class='icon-search'></span>

结果

图标字体没法正常显示,因为全局伪类字体 A 覆盖了图标的 B 字体。

疑问

font-family: B !important 为什么没有起作用, important 应该是优先级最高的呀

我的解答

before 伪元素的 style 是继承了本体元素的 style ,在正常情况下,图标得以显示。 但 !important 是应用在了本体元素的 style 上面,并没有保证 before 伪元素会始终保持这个继承关系。

综上

before 继承的优先级 < 全局设置的伪元素 style

1342 次点击
所在节点    CSS
2 条回复
llb123
2021-11-25 18:14:03 +08:00
确定是 A 覆盖 B 吗
old9
2021-12-06 11:32:29 +08:00
inherited 优先级低
Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/816788

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX