About css and !important tag

18,155

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...

More about this

More about this link 2

!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:

  1. Rules with !important

  2. More specific rules

    .classNameA .classNameB {} /* more specific */
    .classNameB {}
    
  3. 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

Share:
18,155
Juris
Author by

Juris

Updated on June 28, 2022

Comments

  • Juris
    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
    bart s about 11 years
    from C point of view it is funny that not important actually is important
  • Jeroen
    Jeroen about 11 years
    This 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
    FelipeAls about 11 years
    It'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)