CSS The !important Rule
In this example, the color property of elements with the class .example will always be red, regardless of any other conflicting styles.
Maybe One or Two Fair Uses of !important
One way to use !important is if you have to override a style that cannot be overridden in any other way. This could be if you are working on a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles.
Another way to use !important is: Assume you want a special look for all buttons on a page. Here, buttons are styled with a gray background color, white text, and some padding and border:
Example
.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; }You can click on above box to edit the code and run again.
Output
Standard button: CSS Tutorial
Standard button: HTML Tutorial
The look of a button can sometimes change if we put it inside another element with higher specificity, and the properties get in conflict. Here is an example of this:
Example
.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; } #myDiv a { color: red; background-color: yellow; }You can click on above box to edit the code and run again.
Output
Standard button: CSS Tutorial
A link text inside myDiv: HTML Tutorial
A link button inside myDiv: HTML Tutorial
To "force" all buttons to have the same look, no matter what, we can add the !important rule to the properties of the button, like this:
Example
.button { background-color: #8c8c8c !important; color: white !important; padding: 5px !important; border: 1px solid black !important; } #myDiv a { color: red; background-color: yellow; }You can click on above box to edit the code and run again.
Output
Standard button: CSS Tutorial
A link text inside myDiv: HTML Tutorial
A link button inside myDiv: HTML Tutorial