The !important
rule in CSS gives you the ability to override styles, but is this power too much for a lone software developer? Read this article to find out what it is, and when it’s a good idea to use it!
The !important
rule is special because it has the ability to override the natural cascade of CSS styles.
Consider the following HTML/CSS code… What color do you think the text will be?
<div>
<h1 id="title">Sir Chompsalot</h1>
</div>
div h1 {
color: blue !important;
}
div h1 {
color: green;
}
Normally, if we have two CSS rules with identical specificity the latter rule would win. In this case, the earlier CSS rule beats any latter rules simply because it has the powerful !important
rule.
The text is blue!
Using the same HTML markup, what if we got even more specific by targeting the body
tag and h1#title
?
div h1 {
color: blue !important;
}
body div h1#title {
color: green;
}
Will this have the ability to override the !important
rule?
Nope! Wow, the !important
rule is almost too powerful for its own good.
Since !important
contradicts the expected behavior of CSS, it’s generally recommended to avoid using it. If you rely on !important
too often it can cause a lot of unexpected behavior down the road, and new developers will have a hard time debugging their CSS. Why isn’t this text changing color! 😂
Does this mean you should never use it?
As time has passed since !important
was introduced to CSS there seems to be some consensus that it’s really only useful for a single job: dealing with foreign CSS.
Foreign CSS is essentially any CSS that you don’t have direct ability to change or improve yourself. Two practical instances of foreign CSS are:
!important
rules.Since foreign CSS can’t be changed by you (unless you take a job at Instagram to rectify their serious lack of a dark mode), the !important
rule is really your only, and best option.
The folks at Mozilla Developer Network and CSS-Tricks seem to agree that !important
is really only useful for dealing with foreign CSS
If you are really tempted to use !important
, try reflecting on architectural decisions that you can make. Not just your CSS either. This could mean adding new HTML tags, or applying new classes/ids. Engaging in this architecture-centric practice results in high quality code that’s a joy to maintain! 🤓
Have you found other appropriate uses for !important
? Tweet us at @alligatorio and share it with us!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!