Can I override !important?

Winter Bash picture Winter Bash · Jan 22, 2013 · Viewed 16.1k times · Source

What I am trying is setting this CSS on element:

background: red !important;   

But when I try to do this:

 background: yellow;  

it still only shows the red and not the yellow for that one field as I would like it to be (I am not using external CSS).

What I am asking is how to override it, is it possible?

Answer

NullPoiиteя picture NullPoiиteя · Jan 22, 2013

Ans is YES !important can be overridden but you can not override !important by a normal declaration. It has to be higher specificity than all other declarations.

However it can be overridden with a higher specificity !important declaration.

This code snippet in Firefox's parser will explain 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);
}

Good read


Here's an example to show how to override 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;}

and output will be

enter image description here

Also we can not override inline !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;}

the output is

enter image description here

jsFiddle