What is the purpose of the declaration "! Important"?

Asked

Viewed 36,477 times

55

What is the purpose of the declaration !important in the CSS?

body {
  font-size: 12.5px !important;
}

2 answers

64


The statement !important serves to force the CSS to use the property described in that line.

CSS works by hierarchies, a cascade of rules that obey priorities. For example, a property declared in an element directly in the HTML has priority over a closed property in the CSS. In such cases, and in cases of ambiguity where two rules are equal or compete, using !important makes that rule where it is present pervalecer.

To be more specific here is a list of priorities, in ascending order (first is less important), of how CSS works. And once again, the !important is the exception that wins all cases:

Universal selectors, p ex.: *{ }
Selectors of class, p ex.: .minhaClasse{ }
Attribute selector, p ex.: input[type="text"]{ }
Pseudo selector, p ex.: div:hover{ }
Selector of ID, p ex. #minhaID{ }
In the style of HTML, p ex.: style="color: blue;"

This property !important is very useful, but is the same as using "brute force". So it should be used with caution as it can create difficult situations to debug.

A simple example: http://jsfiddle.net/q48hL/1/

#div1 {
  color: blue;
}

#div2 {
  color: blue;
}

#div3 {
  color: red !important;
}

body > div {
  color: blue;
}
<div id="div1">Teste 1</div>
<div id="div2" style="color: green;">Teste 2</div>
<div id="div3" style="color: green;">Teste 3</div>

Note that the !important pervalece even in the third case where there are rules for this element in CSS and HTML.

30

The purpose the !important is to overlap the Rules of precedence.

Example of the operation:

HTML

<p id="a" class="azul">teste</p>

CSS

#a{ color: red;}
.azul{ color: blue !important;}

Without the !important it should be red, because the ID is more specific than a class, due to the use of the same, it is in blue.

You may know a little more about specificity and Rules of precedence taking a look in this tutorial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.