Juris
Juris

Reputation: 43

About css and !important tag

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

Upvotes: 3

Views: 18212

Answers (4)

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32182

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.

Upvotes: 8

Daniel Imms
Daniel Imms

Reputation: 50189

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

Upvotes: 1

Normally, latter CSS declarations overrule earlier. So if you have declared, in the style sheet, a certain background color for a certain element, and the style block on the page itself, or an inline style, declares another background color for that element, the style block or inline style overrules the style sheet.

If you add !important to the declaration in the style sheet, that declaration is not overruled.

Upvotes: 0

Sudip
Sudip

Reputation: 2051

!important sets the priority on the css atributes. If you have two same CSS properties with some different values, one !important mark will set that priority as HIGH.

Upvotes: 0

Related Questions