Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override !important? [duplicate]

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?

like image 782
Winter Bash Avatar asked Jan 22 '13 16:01

Winter Bash


People also ask

Can Important be overridden?

The only way to override an ! important rule is to include another ! important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! This makes the CSS code confusing and the debugging will be hard, especially if you have a large style sheet!

Does inline style override important?

Answer: You cannot override inline CSS if it has ! important . It has higher precedence than the style in your external CSS file. , there's no way to override an inline ! important .

How do you avoid important?

To avoid using ! important , all you need to do is increase specificity. In your case, both of your selectors have identical specificity. The issue is most likely caused by your media query being placed before your "Normal CSS", and thus getting overridden.


1 Answers

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

  • Specifics on CSS Specificity
  • CSS Specificity: Things You Should Know

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

like image 134
NullPoiиteя Avatar answered Oct 14 '22 04:10

NullPoiиteя