!important CSS: How to force one Style above Another CodeUnit 21 JAN 2010

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! :)

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • aaron

    thanks! just what i was looking for.

  • Raquel

    Hello! what happen if both have !important. I’m having a problem because I have to place in our page a third party script. They load the style and overwrite it later but both versions have !important so the first one applies but not the second one. Can I write a third one that overwrites both? how?
    Greetings from Costa Rica!

    • Hi Raquel. Unfortunately from what I understand, you won’t be able to overwrite the style, meaning that you’ll need to try and get your CSS inclusion injected higher up in the document to try and get first parse.

  • tom

    Really helpfull, just what I needed, thanks !

  • I love that t-shirt!

    .ninja {
    color: black;
    visibility: hidden;