CSS !important
By Tony 8.31.2024
Let's say you're setting an element's background color to red using the style attribute in HTML (inline style), and you want to change the background color to orange whenever someone hovers their mouse over the element. If you think putting background-color: orange; in the element's :hover class selector will solve this problem, then you'll be wrong. In this tutorial, you'll learn about CSS specificity, the !important property, and more.
.element {background-color: red;}
div {background-color: orange !important;}
Looking at the two rules above, what will be the background color of
the div element with the element class? Will it be red or orange?
The answer is orange. But if you take off the !important property
behind the orange value, then the element will be red. I know this
sounds confusing, but stick with me. CSS specificity is a set of
rules that tell the browser which value to apply to an element if it
has a property with two conflicting values. Inline styles (style
attribute) are always the most important, meaning that it overrides
any other value set to the same property on an element. Then, it's
the element's id selector, then the class selector, and finally the
element type selector. Now that you have a grasp of CSS specificity,
let's come back to the scenario in the intro above. Because you're
applying the new background color in the class selector, and the
original background color was set using inline style, CSS
specificity tells the browser to ignore the background color set in
the class selector because inline style has a higher importance than
class selector. To solve this problem, you can apply the
!important property at the end of the rule that you want to
set a higher importance. !important makes the rule override
everything, even inline styles. So with the help of !important, you
can make a type selector's rule override an inline style rule!
If you remove the !important property from the div selector in the example above, then you'll see that the element is back to red, because the div selector no longer overrides, which has a higher priority according to CSS specificity. Pro tip: avoid using the !important property everywhere because it messes up CSS specificity and you'll end up with more confusion than solution. Instead, still follow CSS specificity to style an element, and only use !important when absolutely necessary.