With the !important property you mark a CSS property as very important. It can be written after each line to make sure that the particular attribute overrides all previously set values.
To understand the necessity of the !important property, you must first develop a general knowledge of CSS. It may be the case that several styles are defined for one element, for example for a button. First, browsers read the stylesheets from top to bottom. That means if I create two CSS classes “test1” and “test2” below each other to set a background-color and set both classes on my button, the button always gets the color of the second class. If I would write !important behind the background-color of the first class, the color of the first class would be used, because !important assigns a higher importance to this attribute. If I use the !important property for both classes, the natural reading order applies again and the button will take the color of the second class.
.button-class1 {
background-color: blue !important;
}
.button-class2 {
background-color: green;
}
To fully understand the use cases of !important in a more meaningful example, you should be aware of what CSS specificity is. CSS specificity describes the weighting of CSS selectors. If you specify a style inline (style=”background-color: blue), for example, this has a much higher specificity in CSS than a color specification via a CSS class defined in a stylesheet. And it is exactly at those places where the specificity overrides properties of elements where !important can be used. This cancels out all the weighting and gives the property a higher importance no matter what kind of selector or combination of selectors you use.
An application example for this would be to be absolutely sure that all buttons in an application have the same style. Then you could add !important property to those properties and be sure that they won’t be overwritten anywhere else in the applications code.
You should be careful to use this method only in a limited amount or better not at all. Most of the time it leads to even more mistakes, especially if other developers don’t realize that somewhere an !important property was used and the CSS properties don’t behave as they should.