Skip to main content

CSS !important: When and How to Prioritize Styles

What is !important?

The !important is a keyword that can be added to a CSS declaration to give it priority over other CSS rules that may conflict with it. When !important is added to a CSS declaration, it tells the browser to always use that rule over any other conflicting rule, regardless of its specificity.

As an example:

p {
font-size: 16px;
}

.my-class {
font-size: 20px !important;
}

In this example:

  • We have a CSS rule that sets the font size of all p elements to 16 pixels.
  • We also have a CSS rule that sets the font size of elements with the class "my-class" to 20 pixels and includes the !important keyword.

If we have an HTML element that has both the p tag and the "my-class" class, like this:

<p class="my-class">This is a paragraph</p>
  • The font size of this element will be 20 pixels, even though the p tag rule specifies a font size of 16 pixels.
  • This is because the !important keyword in the "my-class" rule gives it priority over any other conflicting rule.
avoid !important

Avoid using !important as much as possible, as it can make it difficult to override styles later on if necessary.