Should I avoid using !important in CSS? - css

Sometimes !important is useful, for example if I have defined common style for all links on the site (selector, say, a), but when I want to override some rules I have the following choices:
Use more specific (longer) selector
Use !important
Which way is better and may be there are some guidelines?

Use !important very, VERY sparingly -- it overrides just about everything, even inline styles, and messes in a less-than-obvious way with the "cascade" of style rules that gives CSS its name. It's easy to use badly, and tends to multiply, particularly when misused. You can easily end up with a element with !important rules that you want to override, at which point you often have to either refactor your styles, or use another !important rule and contribute to the problem.
And once it's spread and you're using it everywhere, you're back up in the same situation you'd be in without it (difficulty in specifying elements specifically enough to override other styles), but you also don't have !important anymore cause everything else is using it too.
When faced with a situation where !important looks appealing -- or worse, one where it's already in use and spreading -- prefer to refactor your CSS if you can. (Frankly, if you need !important outside of a user style sheet, it's usually because your selectors are already way too specific, and/or you're not taking advantage of the C in CSS.) You'd do better to define your basic styles as close as possible to the html or body elements, and when you want to override, use as little specificity as you can get away with. That way, you have plenty of room to make changes. Usually there's a reason you want to override a style, and those cases can quite often be boiled down to a class name, a particular section of the page (read: a particular parent element), etc.
(The only real exception that springs to mind is if the styles you're overriding are effectively out of your control. (If you use a framework that has very strong opinions on how your page should look, for example, you might find it annoyingly difficult to override anything. I've worked with applications that actually inserted their own inline styles, where nothing but an !important rule could override them.) If you don't have full access to the code, overriding and refactoring can easily be more trouble than they're worth. You can use !important to claw back some control, as long as you're aware of the consequences.)

What i can say is that you should try to avoid it as much as you can because it means that there are redundant code, and give an indication that the CSS and styles are not well structured.
But in some cases its a must to use it and no way to avoid.
So just do your best.

Avoid it when you can as this is what most advocate but at the same time it is important.
Have a look at:
The importance of !important in CSS

Related

In CSS, are !important declarations more or less efficient than non !important ones? [duplicate]

I hate them, it defies the cascading nature of CSS, and if you don't use them with care you end up in a loop of adding more !important.
But I want to know are they bad for performance?
EDIT
From the (fast) replies I can conclude it won't have a (significant) impact on performance.
But it's nice to know, even if it's just as an extra argument for discouraging others ;).
EDIT 2
BoltClock pointed out that if there are 2 !important declarations the specs says it will pick the most specific one.
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.
I don't think that !important is inherently bad in terms of how quickly the browser matches rules (it does not form part of the selector, only part of the declaration)
However, as has already been stated, it will reduce the maintainability of your code, and thus likely cause it to grow unnecessarily in size due to future changes. The usage of !important would also likely reduce developer performance.
If you were being really picky, you could also say that !important adds 11 extra bytes to your CSS file, this isn't really much, but I guess if you have a fair few !importants in your stylesheet it could add up.
Just my thoughts, unfortunately I couldn't find any benchmarks on how !important could affect performance.
!important has its place. Trust me on that one. It's saved me many times and is often more useful as a short-term solution, before a longer and more elegant method to your problem can be found.
However, like most things, it's been abused, but there's no need to worry about 'performance'. I'll bet one small 1x1 GIF has more of a performance hit on a web page than !important would.
If you want to optimize your pages, there are many more !important routes to take ;) ;)
What's going on here behind the scenes is that as your CSS is being processed, the browser reads it, encounters an !important attribute, and the browser goes back to apply the styles defined by !important. This extra process might seem like a small additional step, but if you are serving up many requests then you will take a hit in performance. (Source)
Using !important in your CSS usually means developer narcissistic & selfish or lazy. Respect the devs to come...
The thinking of a developer when using !important:
My rocking CSS is not working... grrrr.
What should I do now??
And then !important yeah.... now it's working fine.
However its not a good approach to use !important just because we did not manage the CSS well. It creates lots of design issues -- which are worse than performance issues -- but it also forces us to use many extra lines of code since we are overriding other properties with !important and our CSS becomes cluttered with useless code. What we should do instead is first manage the CSS very well, and not let properties override one another.
We can use !important. But use it sparingly and only when there is no other way out.
I agree with you on not using it because it's bad practice, regardless of performance. On those grounds alone, I'd avoid using !important wherever possible.
But on the question of performance: No, it shouldn't be noticeable. It might have some effect, but it should be so tiny you should never notice it, nor should you worry about it.
If it is significant enough to be noticable then you've likely got bigger problems in your code than just !important. Simple use of a normal syntax element of the core languages you're using is never going to be a performance issue.
Let me answer your question with a retorical question in return; an angle that you probably didn't consider: Which browser do you mean?
Each browser obviously has its own rendering engine, with its own optimisations. So the question now becomes: what are the performance implications in each browser? Perhaps !important performs badly in one browser but really well in another? And perhaps in the next versions, it'll be the other way round?
I guess my point here is that we as web developers shouldn't think about (or need to think about) the performance implications of individual syntax constructs of the languages we're using. We should use those syntax constructs because they're the right way to achieve what we want to do not because of how they perform.
Performance questions should be asked in conjunction with the use of profilers to analyse where the pinch-points are in your system. Fix the things that are truly slowing you down first. There are almost certain to be far far bigger issues for you to fix before you get down to the level of individual CSS constructs.
It does not noticeably affect performance. It does however reduce the maintainability of your code, and therefore is likely to degrade performance in the long run.
Having had to use !important several times before, I have personally noticed no demonstrable performance hit when using it.
As a note see the answer to this stack question for a reason you might want to use !important.
Also I'll mention something that everyone else has failed to mention. !important is the only way to override inline css short of writing a javascript function (which will effect your performance if even only a little bit). So it could actually save you some performance time if you need to override inline css.
hmm... !important or !!important?
Let's go through this step by step:
The Parser has to check for !important for each property, regardless of whether you use it or not - so performance difference here is 0
When overwriting a property, the parser has to check whether the property being overwritten is !important or not - so performance difference here is 0 again
If the property being overwritten is !!important, it has to overwrite the property - performance hit of -1 for not using !important
If the property being overwritten is !important, it skips overwriting the property - performance boost of +1 for using !important
If the new property is !important, the parse has to overwrite it regardless of the property being overwritten is !important or !!important - performance difference 0 again
So I guess !important actually has better performance as it can help parser skip many properties that it won't skip otherwise.
and as #ryan mentions below, the only way to override inline css and avoid using javascript... so another way to avoid an unnecessary performance hit
hmm... turns out out that !important is important
and also,
using !important saves a lot of time for a developer
sometimes saves you from redesigning the whole css
sometimes html or the parent css file is not in your control, so it saves your life there
obviously prevents !important elements from being accidentally overwritten by other !!important elements
and sometimes browsers just don't pick the right properties, without being too specific in selectors, so using !important really becomes important and saves you from writing tonnes of specific css selectors in your css. so i guess even if you use more bytes for writing !important, it could save you bytes in other places. and we all know, css selectors can get messy.
So I guess using !important can make developers happy, and I think that's very important :D
I can't foresee !important impeding performance, not inherently anyway. If, however, your CSS is riddled with !important, that indicates that you've been over qualifying selectors and being too specific and you've run out of parents, or qualifiers to add specificity. Consequently, your CSS will have become bloated (which will impede performance) and difficult to maintain.
If you want to write efficient CSS then you want to be only as specific as you need to be and write modular CSS. It's advisable to refrain from using IDs (with hashes), chaining selectors, or qualifying selectors.
IDs prefixed with # in CSS are viciously specific, to the point where 255 classes won't override an id (fiddle by: #Faust). ID's have a deeper routed problem too though, they have to be unique, this means you can't re-use them for duplicate styles, so you end up writing linear css with repeating styles. The repercussion of doing this will vary project to project, depending on scale, but maintainability will suffer immensely and in edge cases, performance too.
How can you add specificity without !important, chaining, qualifying, or IDs (namely #)
HTML
<div class="eg1-foo">
<p class="eg1-bar">foobar</p>
</div>
<div id="eg2-foo">
<p id="eg2-bar">foobar</p>
</div>
<div class="eg3-foo">
<p class="eg3-foo">foobar</p>
</div>
CSS
.eg1-foo {
color: blue;
}
.eg1-bar {
color: red;
}
[id='eg2-foo'] {
color: blue;
}
[id='eg2-bar'] {
color: red;
}
.eg3-foo {
color: blue;
}
.eg3-foo.eg3-foo {
color: red;
}
JSFiddle
Okay, so how does that work?
The first and second examples work the same, the first is literally a class, and the second is the attribute selector. Classes and Attribute selectors have identical specificity. .eg1/2-bar doesn't inherit its color from .eg1/2-foo because it has its own rule.
The third example looks like qualifying or chaining selectors, but it's neither. Chaining is when you prefix selectors with parents, ancestors, and so on; this adds specificity. Qualifying is similar, but you define the element the selector's applying to. qualifying: ul.class and chaining: ul .class
I'm not sure what you'd call this technique, but the behavior is intentional and is documented by W3C
Repeated occurrances of the same simple selector are allowed and
do increase specificity.
What happens when the specificity between two rules is identical?
As #BoltClock pointed out, If there's multiple !important declarations then
spec dictates that the most specific one should take precedence.
In the example below, both .foo and .bar have identical specificity, so the behavior fallsback to the cascading nature of CSS, whereby the last rule declared in CSS claims precedence i.e. .foo.
HTML
<div>
<p class="foo bar">foobar</p>
</div>
CSS
.bar {
color: blue !important;
}
.foo {
color: red !important;
}
JSFiddle

Update existing design of a website, use of CSS

I'd like to get opinions if this plan is worthwhile or not.
I have an existing site, and some elements have a CSS class defined.
I thought I would append each element that has a class with a new class:
<div class="existingClass">
would turn into:
<div class="existingClass newClass">
Then, if I want to override any attributes in "existingClass", I would do so in "newClass" (because the last class attributes are taken?).
I figure this way, nothing would break, so I do not risk anything because I am not removing "existingClass".
Any problems with this plan?
First know what is in the existingClass. Write newClass in such a manner that it won't break the layout. For knowing what is in the existingClass use tools like firebug to save time.
Indeed this seems to be a good approach, if you don't want to mess editing the already written CSS.
What you must master are CSS precedence rules, also known as CSS specificity.
Some good articles about it:
Specifics on CSS Specificity.
CSS Specificity: Things You Should Know
This is important because when you want to change a style, that chance will be visible only if you follow appropriately those guidelines. If you don't, then you'll face some troubles when rendering your page.

Is !important bad for performance?

I hate them, it defies the cascading nature of CSS, and if you don't use them with care you end up in a loop of adding more !important.
But I want to know are they bad for performance?
EDIT
From the (fast) replies I can conclude it won't have a (significant) impact on performance.
But it's nice to know, even if it's just as an extra argument for discouraging others ;).
EDIT 2
BoltClock pointed out that if there are 2 !important declarations the specs says it will pick the most specific one.
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.
I don't think that !important is inherently bad in terms of how quickly the browser matches rules (it does not form part of the selector, only part of the declaration)
However, as has already been stated, it will reduce the maintainability of your code, and thus likely cause it to grow unnecessarily in size due to future changes. The usage of !important would also likely reduce developer performance.
If you were being really picky, you could also say that !important adds 11 extra bytes to your CSS file, this isn't really much, but I guess if you have a fair few !importants in your stylesheet it could add up.
Just my thoughts, unfortunately I couldn't find any benchmarks on how !important could affect performance.
!important has its place. Trust me on that one. It's saved me many times and is often more useful as a short-term solution, before a longer and more elegant method to your problem can be found.
However, like most things, it's been abused, but there's no need to worry about 'performance'. I'll bet one small 1x1 GIF has more of a performance hit on a web page than !important would.
If you want to optimize your pages, there are many more !important routes to take ;) ;)
What's going on here behind the scenes is that as your CSS is being processed, the browser reads it, encounters an !important attribute, and the browser goes back to apply the styles defined by !important. This extra process might seem like a small additional step, but if you are serving up many requests then you will take a hit in performance. (Source)
Using !important in your CSS usually means developer narcissistic & selfish or lazy. Respect the devs to come...
The thinking of a developer when using !important:
My rocking CSS is not working... grrrr.
What should I do now??
And then !important yeah.... now it's working fine.
However its not a good approach to use !important just because we did not manage the CSS well. It creates lots of design issues -- which are worse than performance issues -- but it also forces us to use many extra lines of code since we are overriding other properties with !important and our CSS becomes cluttered with useless code. What we should do instead is first manage the CSS very well, and not let properties override one another.
We can use !important. But use it sparingly and only when there is no other way out.
I agree with you on not using it because it's bad practice, regardless of performance. On those grounds alone, I'd avoid using !important wherever possible.
But on the question of performance: No, it shouldn't be noticeable. It might have some effect, but it should be so tiny you should never notice it, nor should you worry about it.
If it is significant enough to be noticable then you've likely got bigger problems in your code than just !important. Simple use of a normal syntax element of the core languages you're using is never going to be a performance issue.
Let me answer your question with a retorical question in return; an angle that you probably didn't consider: Which browser do you mean?
Each browser obviously has its own rendering engine, with its own optimisations. So the question now becomes: what are the performance implications in each browser? Perhaps !important performs badly in one browser but really well in another? And perhaps in the next versions, it'll be the other way round?
I guess my point here is that we as web developers shouldn't think about (or need to think about) the performance implications of individual syntax constructs of the languages we're using. We should use those syntax constructs because they're the right way to achieve what we want to do not because of how they perform.
Performance questions should be asked in conjunction with the use of profilers to analyse where the pinch-points are in your system. Fix the things that are truly slowing you down first. There are almost certain to be far far bigger issues for you to fix before you get down to the level of individual CSS constructs.
It does not noticeably affect performance. It does however reduce the maintainability of your code, and therefore is likely to degrade performance in the long run.
Having had to use !important several times before, I have personally noticed no demonstrable performance hit when using it.
As a note see the answer to this stack question for a reason you might want to use !important.
Also I'll mention something that everyone else has failed to mention. !important is the only way to override inline css short of writing a javascript function (which will effect your performance if even only a little bit). So it could actually save you some performance time if you need to override inline css.
hmm... !important or !!important?
Let's go through this step by step:
The Parser has to check for !important for each property, regardless of whether you use it or not - so performance difference here is 0
When overwriting a property, the parser has to check whether the property being overwritten is !important or not - so performance difference here is 0 again
If the property being overwritten is !!important, it has to overwrite the property - performance hit of -1 for not using !important
If the property being overwritten is !important, it skips overwriting the property - performance boost of +1 for using !important
If the new property is !important, the parse has to overwrite it regardless of the property being overwritten is !important or !!important - performance difference 0 again
So I guess !important actually has better performance as it can help parser skip many properties that it won't skip otherwise.
and as #ryan mentions below, the only way to override inline css and avoid using javascript... so another way to avoid an unnecessary performance hit
hmm... turns out out that !important is important
and also,
using !important saves a lot of time for a developer
sometimes saves you from redesigning the whole css
sometimes html or the parent css file is not in your control, so it saves your life there
obviously prevents !important elements from being accidentally overwritten by other !!important elements
and sometimes browsers just don't pick the right properties, without being too specific in selectors, so using !important really becomes important and saves you from writing tonnes of specific css selectors in your css. so i guess even if you use more bytes for writing !important, it could save you bytes in other places. and we all know, css selectors can get messy.
So I guess using !important can make developers happy, and I think that's very important :D
I can't foresee !important impeding performance, not inherently anyway. If, however, your CSS is riddled with !important, that indicates that you've been over qualifying selectors and being too specific and you've run out of parents, or qualifiers to add specificity. Consequently, your CSS will have become bloated (which will impede performance) and difficult to maintain.
If you want to write efficient CSS then you want to be only as specific as you need to be and write modular CSS. It's advisable to refrain from using IDs (with hashes), chaining selectors, or qualifying selectors.
IDs prefixed with # in CSS are viciously specific, to the point where 255 classes won't override an id (fiddle by: #Faust). ID's have a deeper routed problem too though, they have to be unique, this means you can't re-use them for duplicate styles, so you end up writing linear css with repeating styles. The repercussion of doing this will vary project to project, depending on scale, but maintainability will suffer immensely and in edge cases, performance too.
How can you add specificity without !important, chaining, qualifying, or IDs (namely #)
HTML
<div class="eg1-foo">
<p class="eg1-bar">foobar</p>
</div>
<div id="eg2-foo">
<p id="eg2-bar">foobar</p>
</div>
<div class="eg3-foo">
<p class="eg3-foo">foobar</p>
</div>
CSS
.eg1-foo {
color: blue;
}
.eg1-bar {
color: red;
}
[id='eg2-foo'] {
color: blue;
}
[id='eg2-bar'] {
color: red;
}
.eg3-foo {
color: blue;
}
.eg3-foo.eg3-foo {
color: red;
}
JSFiddle
Okay, so how does that work?
The first and second examples work the same, the first is literally a class, and the second is the attribute selector. Classes and Attribute selectors have identical specificity. .eg1/2-bar doesn't inherit its color from .eg1/2-foo because it has its own rule.
The third example looks like qualifying or chaining selectors, but it's neither. Chaining is when you prefix selectors with parents, ancestors, and so on; this adds specificity. Qualifying is similar, but you define the element the selector's applying to. qualifying: ul.class and chaining: ul .class
I'm not sure what you'd call this technique, but the behavior is intentional and is documented by W3C
Repeated occurrances of the same simple selector are allowed and
do increase specificity.
What happens when the specificity between two rules is identical?
As #BoltClock pointed out, If there's multiple !important declarations then
spec dictates that the most specific one should take precedence.
In the example below, both .foo and .bar have identical specificity, so the behavior fallsback to the cascading nature of CSS, whereby the last rule declared in CSS claims precedence i.e. .foo.
HTML
<div>
<p class="foo bar">foobar</p>
</div>
CSS
.bar {
color: blue !important;
}
.foo {
color: red !important;
}
JSFiddle

Resetting and Overrulling CSS under a certain element

I have element that could be injected into any page using a Firefox Addon.
Naturally, it and its ancestors are affected by the CSS rules defined on that page.
I can get so far by simply being explicit about every attribute, but even then my declarations may be overridden by an earlier declaration on the page with greater specificity.
Without making a huge mess of needlessly specific selectors and hanus use of !important, how could I go about resetting all elements' attributes under a given element (div#my_root_container_element) and ensure that my declarations under this parent element apply.
Using an iFrame is one option, but I would rather avoid it if possible - is there another way? Given the application, solutions need only work in Firefox.
Thanks.
Obviously, it seems like this aims to override the "specificity" which is core to CSS in general, but this is the closest I remember ever seeing someone attempt it. It seemed somewhat reputable at the time coming from someone involved with the YUI project:
http://developer.yahoo.com/yui/reset/#code
Using SASS, it's not too unpalatable nesting everything under a div with an ID to achieve sufficient specificity, which is the solution I've opted for.
That said, any !important declaration made in the page CSS will overrule my styles.

Is there an advantage to using very specific selectors in CSS?

I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)

Resources