Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "!important" to save the day (when working with CSS)

Tags:

css

#div p {
    color: red !important;
}
...
#div p {
    color: blue;
}

I understand how !important works, in this case the div will render red because now it has priority (!important). But I can't still figure out an appropriate situation to use it. Does anybody know any example where !important saves the day?

like image 508
alexchenco Avatar asked Jan 11 '10 14:01

alexchenco


People also ask

When should you use important in CSS?

The ! important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the ! important rule, it will override ALL previous styling rules for that specific property on that element!

Why should we not use important in CSS?

important flag are applied to the same element, the declaration with a greater specificity is applied. Using ! important to override specificity is considered a bad practice and should be avoided for this purpose.

How do you avoid important?

To avoid using ! important , all you need to do is increase specificity. In your case, both of your selectors have identical specificity. The issue is most likely caused by your media query being placed before your "Normal CSS", and thus getting overridden.

How do I override a CSS class to another?

To override the CSS properties of a class using another class, we can use the ! important directive. In CSS, ! important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.


3 Answers

Consider this:

#someElement p {
    color: blue;
}

p.awesome {
    color: red;
}

How do you make awesome paragraphs always turn red, even ones inside #someElement? Without !important, the first rule will have more specificity and will win over the second rule.

like image 110
nickf Avatar answered Nov 16 '22 02:11

nickf


Only as a last resort! This is because once used it is hard to override it. My rules of thumb:

  • Never use !important on site-wide css, or when writing a plugin/mashup.
  • Only use !important on page-specific css that overrides site-wide or foreign css (from ExtJs or YUI for example).
  • Always look for a way to use specificity before even considering !important.
like image 39
slebetman Avatar answered Nov 16 '22 04:11

slebetman


!important saves the day in cases where you dont control HTML output and it renders a style='' attribute. Think ASP.NET and other frameworks.

The only way you can then change this styling is by either using javascript or marking your CSS rule as more !important.

like image 20
Martijn Laarman Avatar answered Nov 16 '22 04:11

Martijn Laarman