Saturday, January 8, 2011

What is CSS !important?

 CSS styles always work in order they are read by the browsers. For example if I write –
span{
    color: #f00; (red)
}
span{
    color: #0f0; (green)
}

With the example we all know the green color will be applied to all span elements in our document. But what if I want apply the red color to all span elements in my document without changing the order? I will do this –

span{
    color: #f00 !important; (red)
}
span{
    color: #0f0; (green)
}

Now I will have my all span elements in red color. The !important rule takes precedence over later rule.

Okay fine! In what scenario do I need to use this precedence rule? There are many more places where this !important rule can be used. Such as – .net controls. Some dot net controls create their own CSS at run time with some class names. Since the css file is not available to edit because the classes are being generated at run time. In this case we can take the class name, place it into our CSS file and change the properties we want to change with !important. Then the browsers dare not ignore our change because we have set it on priority.