CSS `!important`

The CSS `!important` rule is used to give a CSS property higher priority, overriding other rules that may have conflicting styles. It is a powerful tool but should be used sparingly to avoid complications in your stylesheet.

Understanding `!important`

When a CSS rule is marked with `!important`, it takes precedence over other rules, regardless of their specificity. This means that even if another rule has higher specificity, the `!important` rule will override it.

Syntax

The syntax for using `!important` is simple. You append `!important` to the CSS property value. Here’s the general form:


/* Syntax */
selector {
    property: value !important;
}

        

Examples

Example 1: Overriding with `!important`


/* CSS Rules */
p {
    color: blue; /* Default color */
}

p.important {
    color: red !important; /* Overrides the default color */
}

This text will be red, despite other color rules.

This text will be red, despite other color rules.

Example 2: Specificity and `!important`


/* CSS Rules */
div {
    color: green; /* Less specific rule */
}

#main-content div {
    color: purple !important; /* More specific but overridden by !important */
}

This text will be purple due to the !important rule.
This text will be purple due to the !important rule.