Why is the ‘!important’ used in CSS?

Why it is use

The !important declaration is a special tool in CSS that lets you give a particular property a higher priority, effectively overriding any other conflicting styles that might be applied to the same element. When you use !important, it ensures that the style will be applied, even if other rules are defined with the same property.

Example:

HTML:

!important Example

.box {
width: 25px; /* Normal width */
height: 100px;
background-color: lightcoral;
}

.box.override {
  width: 30px !important; /* Overrides the normal width */
}

Box
Box with !important

Explanation:

In this example:

  • The .box class has a default width of 25px.
  • The .box.override class sets the width to 30px and uses !important to ensure this width takes precedence over the 25px defined in .box.

So, even though both classes apply to the second div, the width: 30px !important; in the .box.override class will override the width: 25px; from the .box class.

Using !important should be done sparingly because it makes it harder to manage and maintain styles, as it overrides other rules regardless of their specificity. It's best to use it only when absolutely necessary to resolve specific conflicts.