What are the implications of using !important in CSS?
Yes, I'd say your example of using !important
is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.
What's wrong with !important
:
Specificity is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:
button {
color: black;
}
button.highlight {
color: blue;
font-size: 1.5em;
}
button#buyNow {
color: green;
font-size: 2em;
}
On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.
!important
, however, is added at a property level, not a selector level. If, for instance, we used this rule:
button.highlight {
color: blue !important;
font-size: 1.5em;
}
then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the button#buyNow
selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).
An element <button class="highlight" id="buyNow">
would have a font-size of 2em
, but a color blue
.
This means two things:
- The selector does not accurately convey the importance of all the rules inside it
- The only way to override the color blue is to use another
!important
declaration, for example in thebutton#buyNow
selector.
This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One !important
leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one !important
can be a useful short-term solution, it will come back to bite you in the ass in the long run.
When is it okay to use:
- Overriding styles in a user stylesheet.
This is what !important
was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.
- Overriding 3rd party code & inline styles.
Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use !important
sparingly.
- Utility classes
Many libraries and frameworks come with utility classes like .hidden
, .error
, or .clearfix
. They serve a single purpose, and often apply very few, but very important, rules. (display: none
for a .hidden
class, for example). These should override whatever other styles are currently on the element, and definitely warrant an !important
if you ask me.
Conclusion
Using the !important
declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.
There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.
Why using important in css is Bad practice?
I have modified you code. If you want hover like this.
<style type="text/css">
.menustyle a{
position: relative;
}
.menustyle a:before{
position: absolute;
top: -5px;
left: 0;
content: "";
height: 2px;
background-color: #ff0000;
width: 0%;
}
.menustyle > li > a:hover:before{
width: 100% !important;
}
</style>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul id="menu-primary" class="nav navbar-nav menustyle">
<li><a href="#">Home</a></li>
</ul>
</div>
What does !important mean in CSS?
It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'
In normal use a rule defined in an external stylesheet is overruled by a style defined in the head
of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important
'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.
Also, ordinarily, a more specific rule will override a less-specific rule. So:
a {
/* css */
}
Is normally overruled by:
body div #elementID ul li a {
/* css */
}
As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head
or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.
If, however, you add !important
to the less-specific selector's CSS declaration, it will have priority.
Using !important
has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.
It also makes debugging your CSS a nightmare (from personal, empirical, experience).
When to use the !important property in CSS
This is the real life scenario
Imagine this scenario
- You have a global CSS file that sets visual aspects of your site globally.
- You (or others) use inline styles on elements themselves which is
usuallyvery bad practice.
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
Actual real world example?
This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important
makes such situations easier to deal with.
Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...
I suppose you got the idea by now and can come up with some others as well.
When do you decide to use !important
?
I suggest you don't use !important
unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important
styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.
Is !important bad for performance?
It shouldn't have any discernible effects on performance. Seeing Firefox's CSS parser at /source/layout/style/nsCSSDataBlock.cpp#572
and I think that is the relevant routine, handling overwriting of CSS rules.
It just seems to be a simple check for "important".
if (aIsImportant) {
if (!HasImportantBit(aPropID))
changed = PR_TRUE;
SetImportantBit(aPropID);
} else {
// ...
}
Also, comments at source/layout/style/nsCSSDataBlock.h#219
/**
* Transfer the state for |aPropID| (which may be a shorthand)
* from |aFromBlock| to this block. The property being transferred
* is !important if |aIsImportant| is true, and should replace an
* existing !important property regardless of its own importance
* if |aOverrideImportant| is true.
*
* ...
*/
Firefox uses a top down parser written manually. In both cases each
CSS file is parsed into a StyleSheet object, each object contains CSS
rules.Firefox then creates style context trees which contain the end values
(after applying all rules in the right order)
From: http://taligarsiel.com/Projects/howbrowserswork1.htm#CSS_parsing
Now, you can easily see, in such as case with the Object Model described above, the parser can mark the rules affected by the !important
easily, without much of a subsequent cost. Performance degradation is not a good argument against !important
.
However, maintainability does take a hit (as other answers mentioned), which might be your only argument against them.
CSS: !important not overriding other rules
Try this:
.navbar .navbar-nav>li>a {
color: red;
}
Why is !important used so much in style.scss?
!important means that the style preceding it will be "forced" onto the element, despite what other styles may set on it. For example:
.element {
font-weight: bold;
}
.custom-class {
font-weight: normal !important;
}
If you have an <span class="custom-class element"></span>
, it will be displaying a font-weight normal, not bold.
Can I override !important?
Ans is YES !important
can be overridden but you can not override !important
by a normal declaration. It has to be higher specificity than all other declarations.
However it can be overridden with a higher specificity !important
declaration.
This code snippet in Firefox's parser will explain how it works:
if (HasImportantBit(aPropID)) {
// When parsing a declaration block, an !important declaration
// is not overwritten by an ordinary declaration of the same
// property later in the block. However, CSSOM manipulations
// come through here too, and in that case we do want to
// overwrite the property.
if (!aOverrideImportant) {
aFromBlock.ClearLonghandProperty(aPropID);
return PR_FALSE;
}
changed = PR_TRUE;
ClearImportantBit(aPropID);
}
Good read
- Specifics on CSS Specificity
- CSS Specificity: Things You Should Know
Here's an example to show how to override CSS
HTML
<div id="hola" class="hola"></div>
CSS
div { height: 100px; width: 100px; }
div { background-color: green !important; }
.hola{ background-color:red !important; }
#hola{ background-color:pink !important;}
and output will be
Also we can not override inline !important
HTML
<div id="demo" class="demo" style="background-color:yellow !important;"></div>
CSS
div { height: 100px; width: 100px; }
div { background-color: green !important; }
.demo{ background-color:red !important; }
#demo{ background-color:pink !important;}
the output is
Related Topics
Make Content Horizontally Scroll Inside a Div
Fixed Position Relative to Parent Container
Angular 5 File Upload: Failed to Set the 'Value' Property on 'Htmlinputelement'
How to Reuse a Navigation Bar on Multiple Pages
Make an HTML Number Input Always Display 2 Decimal Places
How to Set Space Between Contained Divs
Playing M3U8 Files With HTML Video Tag
How to Remove Specific Text With CSS
Html Text Input Field With Currency Symbol
Css Absolute Position With X Scrolling
How to Load Image (And Other Assets) in Angular an Project
Using HTML Anchor Link #Id in Angular 6
Change the Background Color When an Input Is Checked
Error Error: Formcontrolname Must Be Used With a Parent Formgroup Directive
Add Onclick Event to Svg Element
Mystery White Space Underneath Image Tag