A website can have one, or it can have many Cascading Style Sheets. If you're building using a framework that has its own set of CSS, you're more than likely going to use your own custom sheet to add to (and in cases, supersede) what the framework provides.
While this might duplicate a small amount of data, it's better than editing the CSS from the framework, then having to work out what to save when it comes to update that framework to a new version.
The CSS order is important
In this example, if your custom sheet is imported after the framework's (or any other stylesheet), it will take precendence. So why would you need to override it?
If you're using a platform that adds its own styling, or you have custom code injected into the head of pages, it can be easy to lose track of which styling is coming from where, and every web developer has at some point made a CSS change and found that something else is blocking their change downstream.
Is !important the answer?
Yes, and no. If you want to force a style, you can append the !important
directive at the end of the line (before the semi-colon) to ensure the value for that property 'wins' against any other styling. Is it correct to use it? It can be, but more often than not, once you've confirmed that you're happy with your new styling, it's best practice to work out which styling was overriding it and fix that conflict.
There are cases, however, where that won't be possible. Perhaps a system is inject styling as the page loads, or using javascript. If you have no control over this other styling: !important
is the way to go.
Too many !important rules
If you start relying on !important
it could mean that the CSS is badly structured and difficult to navigate. Worse than that, once you've made something !important
, the only way to override that is to make something of equal importance further down the cascade. If you have a lot of !important
rules... you've essentially removed the 'cascade' from CSS, so it's better to avoid it unless you're unable to.
How to use !important
The following CSS would result in a blue page background with 25px padding in the body
element, because the rule for blue comes after green, and the rule for 25px comes after 50px.
body {
background-color: green;
padding: 50px;
}
body {
background-color: blue;
padding: 25px;
}
To make green take precedence, we add !important
, but note that this is the only property we're adding it to, so we'll retain the padding: 25px;
from the second block.
body {
background-color: green!important;
padding: 50px;
}
body {
background-color: blue;
padding: 25px;
}
Maybe it's not so !important, after all
Using !important
to test styling, or fix an issue where you don't have access to the entire system is fine. Using it once you're happy with that styling (but can't be bothered to find where else you've set the same property) will leave you with messy code and make it harder for yourself when you come back to make more changes in future!