What are the implications of using "!important" in CSS? [duplicate]
Asked Answered
S

9

219

I've been working on a website for a few months, and a lot of times when I've been trying to edit something, I have to use !important, for example:

div.myDiv { 
    width: 400px !important;
}

in order to make it display as expected. Is this bad practice? Or is the !important command okay to use? Can this cause anything undesired further down the line?

Schematic answered 14/9, 2010 at 7:23 Comment(2)
Using the !important keyword in CSS is a way to prevent other meddlesome programs from taking liberties to interpret your html/css in a way other than what you want. For example when someone goes to print your html/css to paper-and-ink, they often want the background-color property to be white to save ink. So the program overrides your background-color property. This !important keyword prevents that. I find these sorts of keyword switches irritating, like a debate between two teenagers that goes: yes! no! Yes! No! YES! These sorts of keywords indicate disharmony and a power struggle.Brokaw
I've used !important sparingly when a linked css file is unavailable to edit in a CMS environment. This highlights a need maybe to allow all editors to have a way to contribute more to the development of the central assets.Bashkir
H
286

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:

  1. The selector does not accurately convey the importance of all the rules inside it
  2. The only way to override the color blue is to use another !important declaration, for example in the button#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.

Handwriting answered 14/9, 2010 at 7:31 Comment(11)
I understand. It's difficult to maintain an !importantless CSS file in this situation though. Of course I have added all new element selectors to the end of the the document, but sometimes it is just necessary to override some inherited values, no matter how specific my selector is, it's all that works. Thanks :)Schematic
use firebug to check why another style rule is taking precedence. Then you can make sure yours is more specific, and override it that way.Shackleford
+0. Clarification/correction: user !important rules take precedence over anything else, including author !important rules: w3.org/TR/CSS2/cascade.html#cascading-orderRosanne
Normally it's really not necessary to use !important. But sometimes when you have to overwrite styles that have been set inline (e.g. by a JavaScript widget) it's the only way to change the css when you don't want to dive into JS.Shaft
The FUD is strong with this answer. There's nothing wrong with using !important - there is, of course, plenty wrong with misusing it.Place
It does not break cascading. It does not prevent user styles from being applied. Those are misunderstandings of the rules of CSS. !important is something you should use sometimes. It's only "bad practice" in the hands of a developer who doesn't understand what it does.Place
@Place I completely rewrote the answer, it was very outdated and misinformed. Thoughts on the revision?Handwriting
@StephanMuller agree with the specifics, but not the headline / conclusion. The fact that !important isn't intended to be used everywhere doesn't mean it's "bad practice" any more than, say, using element IDs in selectors. You wouldn't do it for every rule - that would lead to some difficult to maintain code - but it certainly has its place, so I couldn't imaging calling it bad practice.Place
In stackoverflow.com/questions/29949824 you mentioned adding external refs for @LcSalazar, so here’s a link to CSS Lint’s explanation of their ‘Disallow !important’ rule, which links to additional references: github.com/CSSLint/csslint/wiki/Disallow-!important HTHAbana
As an aside, element qualification (div.myDiv) is generally unnecessary, and should be avoided (→ .myDiv). That way you can use it to add additional specificity when needed (+ add a comment to note this).Abana
!important will have a higher importance; that's weird to me hehehAerostatic
B
18

!important forces the statement to always apply, doing these things:

  • even if the selector is less specific and lower level, it now beats higher specificity selectors
  • if there are further occurrences of that statement that would normally override that one, it does not override the important statement any more

Most of the time, !important can be avoided because specificity of selectors handles which one takes effect, which is the idea of cascading styles. However, there are some situations (can't quite remember the exact one) where the specificity isn't that logical and I have to force !important on the statement.

Reasons not to use/avoid !important?

  • prevents users from using custom stylesheets (which now can't override the rules that are marked as important) which breaks accessibility for some people
  • makes code more difficult to read because the mind normally takes specificity quite easily, but remembering what is !important makes it harder to read
Bosquet answered 14/9, 2010 at 7:26 Comment(5)
Actually, !important works on most IEs (IE6 has a slightly incorrect implementation). For IE support I think you're referring to inherit, which indeed only works since IE8.Haversine
I believe that IE 6 and 7 do not work with !important; see this page: evolt.org/node/60369Bosquet
!important does not work only when specifying it on a repeating property in the same rule in IE6. IE7 handles that correctly.Haversine
I don't care about IE6, but 7 and 8 I have to support, being that most of our customers use IE7 and 8, even some people in this office still use it, despite my insistent pressing for them to change to FF or Chrome.Schematic
This is not correct; user !important rules take precedence over site !important rules, but site normal rules take precedence over user normal rules. (So if a site sets some value for a CSS property, a user style can't override it without using !important.)Selfcontradiction
O
10

I think it is important that we touch on this again, here at the end of 2014 when more rules are being added into the working draft, it is so important not to impose restrictions upon your users. I have wrtten this small example to explain a possible scenario in which such a thing takes place. This is taken from a REAL website I have visited on the web, and I see it, sadly, more often than not.

Form Text Editor Fields

You have a website, and your website depends on filling out forms and editing text. To try to minimize eye strain you try to go with a style you think everyone will be okay with, and since your users mainly visit at night, you decide to make your background color to be white, and then make the text color to be black. The form is blank by default, so you type in text (this time) to make sure it works:

...
background-color: black; /* I forgot important here, but it works fine on its own */
color: white !important;
...

A few months later, users complain that white-on-black is too eye straining but the other half love it, what do you do? you add a custom theme that uses !important to override the internal styles so that BOTH parties are happy, which is what it is SUPPOSED to be used for:

...
background-color: white !important;   
color: black !important;
...

Now, what happens here? What did you expect. If you properly remember the !important tags in the first set, you would have noticed it didn't work and probably remembered that you needed to delete the !important tags off. BUT you forgot one..

RIGHT, you get white text on white background, and the user can no longer read your webpage at all if they try to use this new style (assuming you kept it).

Of course, You don't realize this because the textbox is empty. And You ASSUME that it will work! (Assumption is a developer's worst enemy, it's right up there with pride and arrogance).

Make and Follow Self Implied Rules

So, the basic rule should be only use !important when designing OVERRIDES to an original complete set of css rules. Remember that it is meant for exceptions and disturbs the natural order and meaning of css in the first place. In MOST cases you will not need to use it at all.

Know How Users Customize Their Colors

With the existence of such tools as extensions and the presence of sites like 'userstyles.org' and it's stylish counterpart, you run the risk of alienating your users by using the !important tag at all! Keep in mind that stylish will not override them.

Never Restrict Your Visitors

If you use !important on a style, make sure you make it possible for the user to turn that style off (and i dont mean via the web browser's internal 'on/off' switch). And for heavens sake don't make it DEFAULT.

Ads

People are less and less using stylish for ad removal, so I don't think protecting ads with !important really is an issue here. It will just annoy someone trying to customize your site.

Opprobrious answered 28/11, 2014 at 13:20 Comment(1)
There is no point in trying to use !important to prevent users from customizing your site. Because: Normal site rules already take precedence over normal user rules; but !important user rules take precedence over anything, including site !important rules.Selfcontradiction
S
10

A little late to this question but it's saying "no matter what other styles are applied, ignore them and use this one". You may find it a little confusing with the ! infront (of the !important) because thats a not operator in javascript but in css it's called a delimiter token that just says to take priority. Heres an example.


Without !important:

.set-color{
  color: blue;
 }

.set-color{
  color: red;
 }

outputs RED


!important on bottom attribute (of same)

.set-color{
  color: blue;
 }

.set-color{
  color: red !important;
 }

outputs RED (would have been red anyways)


!important on top attribute (of same)

.set-color{
  color: blue !important;
 }

.set-color{
  color: red;
 }

outputs BLUE (says ignore red, use blue)


Spermiogenesis answered 29/2, 2016 at 5:8 Comment(0)
T
8

For me, using !important is a bad CSS practice. It disrupts the natural flow in applying the css rules where in properties are applied from top to bottom. With !important, the property will now give priority to the latest important value.

It's just like using the goto keyword in scripts. Though its are perfectly legal, it's still best avoided.

Telluride answered 14/9, 2010 at 7:49 Comment(0)
F
5

I wouldn't advise you to use it unless it's a necessity, which sometimes might be the case with you, as you're working on an existing project. But try to stay away from it and use as little !important as possible.

The problem is if you use too many of them then one might inadvertently overwrite the other. Your code is also much less legible and anyone who comes after you to maintain this will tear his/her hair apart, as trying to find !important every time you do something in the CSS is a royal pain.

Check this: http://webdesign.about.com/od/css/f/blcssfaqimportn.htm

Flotsam answered 14/9, 2010 at 7:29 Comment(1)
"This is a change from CSS1 to CSS2. In CSS1, author !important rules took precedence over user !important rules. CSS2 changed this to make the user's style sheet have precedence." -Ah, I didn't know that.Handwriting
O
3

Well, i think using !important is sometime "must to do job" if you want overdraw wp-plugins default properties.

I used it just today and it was the only way to finish my job. Maybe is not good way to do something but sometime is the only way to do it.

Oakland answered 2/2, 2016 at 13:28 Comment(1)
Before anyone chooses to recommend deletion of this post, this is a valid attempted answer. This post should not have been flagged and should not be recommended for deletion in the LQPRQ. See: You're doing it wrong: A plea for sanity in the Low Quality Posts queue and Your answer is in another castle: when is an answer not an answer?Anacreon
S
0

!important is a factor, That can vain your code for something that is overridden

the ! in it does not mean Logical not, such here it gets disconcerting with that among that code. !important is frequently a colossal mishap in computing.

For Example if you want to make it display: block; but you've already defined display: none;:

p {
   display: none;
   display: block !important /*Now overriden*/;
}
<p>Some Paragraph</p>

!important is a best avoided keyword, When to use it, It may be a Influential time, Please click this link to see when to use !important, !important Style Rule - CSS-Tricks

Avoid using !important

no madder what

Schweinfurt answered 5/12, 2018 at 17:58 Comment(0)
S
0

The problem with !important is that with CSS you MUST in all cases try to avoid deep selecting (more priority), because in the future you or someone else (often for big projects) will need to override these styles WITHOUT changing the original style and then this one will have limited freedom to do that. He will need to use !important, too with deeper selector.

Shrift answered 14/6, 2019 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.