!important CSS: How to force one Style above Another

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

You might also enjoy:

  • Let's start this off with a quick, NEVER should you be suppressing errors instead of trying to resolve the scenarios in which an error can occur. However ...
  • If for instance you have just used a jQuery selector to grab a whole lot of objects and now realize that in actual fact you only want to effect the first ob ...
  • Sometimes you just don't want to use the good old anchor tag and want to use a tag instead, but at the same time, you want people who mouse-over your span ...
  • Using jQuery to highlight a table row on mouse over is pretty simple to achieve, and today I'll quickly demonstrate how you can achieve this neat effect usi ...
  • For a long time there has been the excellent SourceForge Excel Reader PHP class available to developers wishing to add Excel parsing to their offerings, but ...

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code and tagged cascading, , force, important. Bookmark the permalink.
    blog comments powered by Disqus