Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS !important Rule

CSS !important Rule

What is !important

The !important rule in CSS is used to increase the weight of a style.

!important is not related to specificity, but it is directly related to the final result; when an !important rule is used, this declaration overrides any other declaration.

Example

#myid

{

background-color:

blue

;

}

.myclass

{

background-color:

gray

;

}

p

{

background-color:

red

!

important

;

}

Try it »

In the example above, even though ID selectors and class selectors have higher specificity, the background color of all three paragraphs appears red, because the !important rule overrides the background-color property.

Important Notes

Using !important is a bad habit and should be avoided, because it breaks the inherent cascade rules in the stylesheet, making debugging bugs more difficult.

When two conflicting declarations with !important rules are applied to the same element, the declaration with higher specificity will be adopted.

In the following example, when we look at the CSS source, it is not clear which color is the most important:

Example

#myid

{

background-color:

blue

!

important

;

}

.myclass

{

background-color:

gray

!

important

;

}

p

{

background-color:

red

!

important

;

}

Try it »

Usage recommendations:

When to use !important

If you want to set a site-wide CSS style on your website, you can use !important.

For example, if we want all buttons on the site to have the same style:

Example

.button

{

background-color:

#8c8c8c

;

color:

white

;

padding:

5

px

;

border:

1

px

solid

black

;

}

Try it »

If we place the buttons inside another element with higher specificity, the appearance of the buttons will change and properties will conflict, as in the following example:

Example

.button

{

background-color:

#8c8c8c

;

color:

white

;

padding:

5

px

;

border:

1

px

solid

black

;

}

#myDiv

a

{

color:

red

;

background-color:

yellow

;

}

Try it »

If we want all buttons to have the same appearance, we can add the !important rule to the buttons' style properties, as shown below:

Example

.button

{

background-color:

#8c8c8c

!

important

;

color:

white

!

important

;

padding:

5

px

!

important

;

border:

1

px

solid

black

!

important

;

}

#myDiv

a

{

color:

red

;

background-color:

yellow

;

}

Try it »