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 ...