About css and !important tag
Solution 1
The !important
rule is a way to make your CSS cascade
but also have the rules you
feel are most crucial always be applied. A rule that has the !important
property
will always be applied no matter where that rule appears in the CSS document.
So if you wanted to make sure that a property always applied, you would add the !important
property
to the tag.
So, to make the paragraph text always red, in the above example, you would write:
p { color: #ff0000 !important; }
p { color: #000000; }
Using !important
in your CSS usually means you're narcissistic & selfish or lazy. Respect the devs to come...
!important
is a part of CSS1.
Solution 2
What is it?
!important
overrides other styles that don't have it. Here is a basic order of priority for CSS:
-
Rules with
!important
-
More specific rules
.classNameA .classNameB {} /* more specific */ .classNameB {}
-
The order of the rules
.classNameB {} .classNameB {} /* takes priority */
Example
.classNameB .classNameA {
background-color: red;
}
.classNameA {
background-color: blue !important;
}
Despite .classNameA
being more specific in the first rule, the background-color
of .classNameA
is blue
because of !important
.
Should you use it?
No, avoid it at all costs. Only ever use it if it's absolutely necessary and if you find yourself in a situation where it is, consider refactoring your CSS. The reason for this is because it's difficult to change your CSS when you have !important
rules all over the place. It's also an indicator of bad CSS design.
Further reading
- Smashing magazine - !important CSS Declarations: How and When to Use Them
- CSS Tricks - When Using !important is The Right Choice
Juris
Updated on June 28, 2022Comments
-
Juris almost 2 years
Can anybody explain what in reality do !important in css styles?
I when i lok on other site css sometimes they use it, but why? I'm not realy understending the !important "job" :D
Thank You...
-
bart s about 11 yearsfrom
C
point of view it is funny thatnot important
actually is important -
Jeroen about 11 yearsThis is not correct, an
!important
rule will not "always be applied no matter where that rule appears". These rules merely take precedence over rules without!important
. The!important
rules am sich cascade as well, so different!important
rules can override eachother normally. -
FelipeAls about 11 yearsIt's more like 1.a instructions with !important and more specific selector (than another instruction also with !important but a less specific selector) / 1.b instructions with !important and order of the rules they appear in. Then your existing 2 and 3. Also inline styles and CSS user with !important (always wins) and without !important (wins over UA default CSS, loses against CSS author with or without !important)