The CSS !important Specifier

One of the challenges people new to Cascading Style Sheets face is figuring out why the rule they just coded doesn’t seem to be doing anything. Once you start building more complex websites, it’s likely that several rules will apply to a single HTML tag. In some cases, all of the styles can be applied; for example, you could say that everything in your content area will be colored green, then say that your paragraphs will have size 12 font, and you’ll end up with green, size 12 text. But what happens when styles contradict?

As it happens, you can (mostly) figure out which style will take precedence by doing a little math. If you’ve used an inline style applied directly to the element in question, it has weight 1000 (and almost certainly wins). Otherwise, add up 100 for each ID in the style, 10 for each class, and 1 for each element. Psuedo-classes (such as :hover) cound the same as real classes, as do attribute selectors (such as [type=”submit”]) Psuedo-elements (such as :first-letter count the same as real elements. Highest number wins!

In case of a tie, whichever specifier is encountered last is considered to be more important. This applies to both internal and external styles, so if you import several external style sheets, whichever one is important last will win all ties.

So what do you do if your new style doesn’t seem to be working? Well, from a practical standpoint, the first thing to do is make sure you haven’t mistyped anything, maybe mistyped a class name or used a . where you need a #. After that, the best thing to do is to make your selector more specific – that is, add more IDs and classes to give it greater weight –  so that it will override the less specific selectors.

However, if you have a style that absolutely MUST apply in all situations, you can use the !important selector.  (Does anybody else read that as saying “not important”?) This selector applies only to one particular property, not the entire block. For example, suppose I have this code:

#container {
color: black !important;
font-family: ‘Cambria’, ‘Times New Roman’;
}

#content {
color: red;
font-family:Arial, Helvetica, sans-serif;
}

Any text that is inside the content box, which is inside the container, will be in Arial…but it will be black.

The !important statement should be used only sparingly; not only do you not want two !important statements to ever apply to the same line of code, but it’s a real pain to have your selector not working because there’s an !important line somewhere in your external style sheets!