CSS中的特异性仅涉及选择器,而不涉及它们关联的声明。 !important
适用于声明,因此它本身在特异性方面没有作用。
但是,!important
会影响级联,这是为某个元素计算样式的总体过程,当多个相同的属性声明应用于它时。或者,正如Christopher Altman所描述的那样:
!important
就像一张黑桃牌,它可以打败所有特异性点。
但不仅如此:由于它总体上影响了级联,如果您有多个具有匹配同一元素的!important
声明的!important
选择器,则选择器特异性将继续应用。同样,这只是由于有多个规则应用于同一元素。
换句话说,在同一样式表(例如,同一用户样式表、同一内部作者样式表或同一外部作者样式表)中具有不同选择器的两个规则中,具有最具体选择器的规则适用。如果有任何!important
样式,则具有最具体选择器的规则中的样式获胜。最后,由于您只能拥有重要或不重要的内容,因此在影响级联方面无法再进行更深入的操作。
这里是关于!important
的不同用法及其应用的示例:
The !important
declaration always overrides the one without it (except in IE6 and older):
/* In a <style> element */
#id {
color: red !important;
color: blue;
}
If there is more than one !important
declaration in a rule with the same level of specificity, the later-declared one wins:
/* In a <style> element */
#id {
color: red !important;
color: blue !important;
}
If you declare the same rule and the same property in two different places, !important
follows the cascading order if both declarations are important:
/* In an externally-linked stylesheet */
#id {
color: red !important;
}
/* In a <style> element appearing after the external stylesheet */
#id {
color: blue !important; /* This one wins */
}
For the following HTML:
<span id="id" class="class">Text</span>
If you have two different rules and one !important
:
#id {
color: red;
}
.class {
color: blue !important;
}
That !important
always wins.
But when you have more than one !important
:
#id {
color: red !important;
}
.class {
color: blue !important;
}
The #id
rule has a more specific selector, so that one wins.
!important
声明时,特异性才会起作用。否则,!important
声明每次都会获胜,无论特异性如何。 - MrWhite!important
的样式。 - techie_28!important
是一张黑桃牌,它能够压倒所有的特异性点数。对于你提出的问题,!important
将覆盖数百个 id/classes。!important
重置层叠。因此,如果你在另一个 !important
下使用了 !important
,第二个实例就会生效。!important
的理解。!important
,你需要退后一步,检查你是否做错了什么。 !important
意味着你正在违反 CSS 的层叠。你应该只在极少数情况下使用 !important
。!important
,那么你可能做错了什么。最后一点加1分。 - Spudleydiv#id.class
比div#id
更具体。这里有一个链接,可以很好地解释特异性。我曾经在Stack Overflow上看到过它的链接。 - My Head Hurts
property: value !important
,而不是important!
(就像您问题标题中所写的)或property: value; !important
(就像您第一个演示中的代码)。在您第二个演示中,您编写了div#green
,它正在寻找<div id="green">
,但在您的演示中不存在该元素。总之,您需要确保了解更基本的问题,然后再担心!important
的细微差别。 - thirtydot