我可以覆盖!重要吗?

时间:2013-01-22 16:05:23

标签: html css css3 stylesheet

我正在尝试在元素

上设置此CSS
background: red !important;   

所以当我尝试这样做时。

 background: yellow;  

(我没有使用外部css)它仍然只显示那个字段的红色而不是黄色,就像我希望的那样。

我要问的是如何覆盖它,是否可能?

3 个答案:

答案 0 :(得分:33)

Ans !important可以被覆盖,但您无法通过正常声明覆盖!important。它必须比所有其他声明具有更高的特异性。

但是,可以使用更高的特异性!important声明来覆盖它。

Firefox解析器中的这段代码片段将解释how it works

if (HasImportantBit(aPropID)) {
  // When parsing a declaration block, an !important declaration
  // is not overwritten by an ordinary declaration of the same
  // property later in the block.  However, CSSOM manipulations
  // come through here too, and in that case we do want to
  // overwrite the property.
  if (!aOverrideImportant) {
    aFromBlock.ClearLonghandProperty(aPropID);
    return PR_FALSE;
  }
  changed = PR_TRUE;
  ClearImportantBit(aPropID);
}

好读


这是一个展示如何覆盖CSS

的示例

<强> HTML

<div id="hola" class="hola"></div>

<强> CSS

div { height: 100px; width: 100px; }
div { background-color: green !important; }
.hola{    background-color:red !important; }
#hola{    background-color:pink !important;}

并输出

  

enter image description here

此外,我们无法覆盖内联!important

<强> HTML

<div id="demo" class="demo" style="background-color:yellow !important;"></div>

<强> CSS

div { height: 100px; width: 100px; }
div { background-color: green !important; }
.demo{    background-color:red !important; }
#demo{    background-color:pink !important;}

输出

  

enter image description here

jsFiddle

答案 1 :(得分:15)

w3 spec中所述,!important声明不会改变特异性,而是优先于“正常”声明。实际上,这样的声明只能在它们之间“竞争” - 因此,你可以用另一个更高特异性的!important声明覆盖你的声明:

/*
 these below are all higher-specificity selectors and, if both 
 rules are applicable to the same element, background colour
 will be set to "yellow":
 */
.some-class.some-other-class, div.some-class, #some-id {background: yellow !important;}
.some-class {background: red !important;}

还有一个需要考虑的声明顺序 - 如果CSS的选择器具有相同的特异性,那么CSS中的声明将优先于早期声明。

值得注意的一个案例是它与内联声明发生冲突。违反直觉(但完全符合规范),!important值将出现在最前面!这意味着如果你有

<style>
  #secret-container {display:none !important;}
</style>
<script>
  $('#secret-container').show();//using jQuery etc.
</script>
<div id="secret-container">...</div>

有问题的div将保持隐藏状态!内联规则优先于!important规则的唯一方法是将!important应用于其中。我会让你判断practice_ಠ

的做法有多好

虽然有no overriding inline !important

答案 2 :(得分:12)

!important会覆盖background: yellow;尽量避免使用!important。看看css特异性。 http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/