In CSS, how do you force a particular style declaration to take precedence over all others that have come before or after it?

Remember the very nature of Cascading Style Sheets is to cascade. Hierarchy is important and if a style is read by the browser after a previous style declaration affecting the same element has already been submitted, then I’m afraid it will be that last style read that will be applied.

But how about when you want to dynamically adjust styles? Or what if you want a particular style to always crow king, even if it wasn’t the last style read in?

Well luckily CSS brings with it the nifty !important rule which, although primarily targeted as a usability tool (Google the concept of User versus Author stylesheets), hands us the power to force a particular style to be applied, regardless of whether or not it gets overridden at a later stage.

To give an example as to its usage, let’s look at the following style declaration:

p { color: #ff0000; }
p { color: #000000; }

This stylesheet will result in all paragraph text beingĀ  printed in black, despite the first attribute assigning it’s color to that of red.

However, let’s add the !important rule into the mix:

p { color: #ff0000 !important; }
p { color: #000000; }

Believe it or not, all paragraph text has now changed from the previous black to red. Fantastic, exactly what we were hoping for! :)