It’s !important

Funny how after years of playing with CSS I hadn’t come across the !important  attribute. To be honest that was probably a Good Thing and should as a rule be treated just like ‘C’s “goto” statement – just don’t do it, there’s always a better way.

The !important  attribute will, I guess, be read by most programmers as “NOT important”, but this being CSS actually means it IS important and can be used to force a CSS rule to take precedence regardless of the structure of the CSS. Lets use an example:

Not the outcome we expected

Not the outcome we expected

The html is a basic start point for a menu and hopefully it is clear that I wanted the text “Foobar” to be in blue not red ! The ID selector (test1) takes precedence over the class (test2).

Enter  !important . Lets modify the class ‘test2′.

Applying the !important fix.

Applying the !important fix.

Now we get the correct blue colour. Basically !important  has told the CSS “I don’t care what you [the css] think it is, I’m telling you what it is!”. But have I done the right thing ? Well, if you start liberally sprinkling this kind of hing through your CSS - and especially if you have multiple and / or large CSS files, you will soon run into clashes and perhaps other CSS that is unintentionally affected – pity the poor person who had to maintain it (and lets face it, that person could be you) !

What should I have done instead of this filthy hack?

I could change “test2″ from a class to a selector (as per test1). However if (as in this case) I’m creating a menu with multiple second menus (that’s actually what test2 represents) I dont want test2 to be an ID. Similarly I could modify things so that both “test1″ and “test2″ are classes – but then there should be only one main menu (which is what test1 actually represents) so I’d rather keep test1 as a selector.

Nope, a proper selector is what you want:

Using a full selector

Using a full selector

OK, so this is all basic CSS stuff but I wanted to make the point that if you think you need !important  then you’re probably doing it wrong. So, it’s of no use then ? Well, I didn’t say that. It is very useful for debugging; in practice the CSS for a proper menu is way more complex than the simple code presented above and I certainly began to question my sanity when one of my menus stubbornly refused to pick up the correct font size. Was my selector even being seen ? Was there a syntax error that was effectively causing some of my CSS to be ignored ? A quick !important added to the font size quickly “fixed” the problem thus ruling out the two causes leaving the only cause being me not fully understanding the structure ! Damn.

 

 

 

Leave a Reply