CSS !important

The !important declaration in CSS is a way to make a specific property and value pair the most important in the style sheet, overriding any other styles that may apply to that element, regardless of specificity or the order in which the rules appear.

1. Usage

The !important keyword is added after the value of a CSS property, before the semicolon:

selector {
  property: value !important;
}

Try It Now

2. Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS !important Example</title>
  <style>
    p {
      color: blue;
    }
    .override {
      color: red !important;
    }
    .another-rule {
      color: green;
    }
  </style>
</head>
<body>
  <p class="override another-rule">This text will be red due to the !important rule.</p>
</body>
</html>

Try It Now

3. Explanation

In the above example:

  • The p element is initially styled with color: blue;.
  • The class .override sets color: red !important;.
  • The class .another-rule sets color: green;.

Despite the .another-rule being applied after .override, the color: red !important; takes precedence, and the paragraph text appears red.

4. When to Use !important

  • Override Inline Styles: Inline styles added directly to an element can be overridden by using !important.
  • Override External Libraries: If you need to override styles from third-party libraries without editing their code, !important can force your styles to apply.
  • Quick Fixes: Useful for quick debugging or when you don’t have control over all styles.

5. When to Avoid !important

  • Maintainability: Overusing !important can make the CSS difficult to maintain and debug.
  • Specificity Confusion: It can lead to confusion in understanding why certain styles are applied.
  • Cascading Issues: It goes against the natural cascading rules of CSS, which are crucial for predictable styling.

6. Best Practices

  • Use Sparingly: Rely on specificity and the cascade order before resorting to !important.
  • Comment Usage: When using !important, comment on why it’s necessary to help maintain the code.
  • Alternative Solutions: Try to increase specificity or rearrange the order of your styles to achieve the desired effect without !important.

By understanding the implications and correct usage of !important, you can use it effectively in your CSS when absolutely necessary, ensuring your styles are both robust and maintainable.