What is the reason for !important?

Neil E.

Active member
Yes I know it fixes some stuff, but why is it necessary? I have used it to fix things that should have worked fine in EXTRA.css. How does it operate?
 
Ok mate.

say you have:
Code:
a{
color: black;
}

That makes every link Black.

However in one section I want a link to be Blue.
Code:
<div class="box"><a href="/">Blue Link</a></div>
That will still be black, however if I add this CSS to it:

Code:
a{
  color: black;
}
 
.box a{
color: blue !important;
}

It will make the link blue in that div. It tells the browser, hey it's IMPORTANT to have that link Blue. Therefore overwrites the Black link with a Blue link.
 
Ok mate.

say you have:
Code:
a{
color: black;
}

That makes every link Black.

However in one section I want a link to be Blue.
Code:
<div class="box"><a href="/">Blue Link</a></div>
That will still be black, however if I add this CSS to it:

Code:
a{
  color: black;
}
 
.box a{
color: blue !important;
}

It will make the link blue in that div. It tells the browser, hey it's IMPORTANT to have that link Blue. Therefore overwrites the Black link with a Blue link.
That is not entirely true. The second rule is more specific than the general a rule, so that will always override the general a rule, even without the !important tag. Important is used to override CSS other places. Let us say you have blah.css and style.css. blah.css is only loaded on blah.html and style.css is loaded on every page. In style.css you have a rule to define colors of every link (a { color: yellow; }), yet you want the color in blah.html to be different, so in blah.css you put in a a { color: red !important; }. This will make the color of links in blah.html red, yet they are yellow on other pages where blah.css isnt loaded.

In most cases it is better to increase specificity of your css rather than use important, however if you are doing styling in extra.css you are most likely overriding the default behaviour of the style you are using, and then are forced to either change the default rule or override it with !important in extra.css.
 
Top Bottom