Tuesday, December 1, 2009

Usage of !important

As you aware, when multiple styles are defined then the concept of specificity helps to determine which style to be applied.

Similarly, when you want to diagnose why a particular style is not being applied, then you can use !important.

For example, i want all h1 text to be in upper case. and i use this style

h1 {
text-transform:uppercase;
}

When i reload it is not working, because there was a style already defined saying this somewhere in my style

#content h1{background-color:green;
text-transform:lowercase;
}

Since this style is having higher specificity value (0101) compared to earlier style (0001), this is being applied. It is easy to debug, bcoz my css file is smaller and the style i am applying is a simple one.

I am not doing any complex things like setting up margins, paddings which is difficult to identify. But imagine, when you are working on a project with many css files being included and you are doing complex things, you may be in a dilemma whether the style you have written is having an error or is it the problem with other styles overriding.

To overcome this , you can use !important like this
h1 {
text-transform:uppercase !important;
}

This will override any other style irrespective of whatever the specificity value is and will make the text in h1 to uppercase. This would eliminate one of my doubt of syntax or style being wrong.

If you are using !important and still you don't see any effect, then it means that there is a error in your style syntax, may be you would have misspelled the element descriptor or Id or Class.

This way, the !important will help you diagnose the issue.

It is advisable and very important to avoid using !important for styling. You should use it only for debugging purpose. For example, the above one can be achieved by giving the same specificity value or writing this style in the same place where it is defined earlier.

Otherwise, later you may have to override this again and you will end up mentioning many !importants in your style.css

Also, Remember if you see !important in your style, then it means you are getting lazy ;)

Hope this may help some of the developers .

All the best

No comments: