Trying to get around CSS Hacks

Recently I have been playing around with a monster CSS file at my new job. The CSS file has been there for a few years and as had a few junior designers working on it from time to time. The problem is that when they come to edit it seems that no-one decided to check if there was previous tag, they just added in a new one, this then turns in to a monster 1600 + lines of CSS for one site. Granted it’s only 45k in size but when you also have to load the JavaScript and the jQuery and the images, etc, etc, it gets a bit ridiculous.

When I was going through the file I came across endless hacks mixed in with the invalid CSS, the vast majority of the hacks were the good old star hack. Things like *margin-left:20px; for example. Don’t get me wrong these work great for IE6+ if there is a display issue, however this isn’t valid code. W3C will not validate your CSS if you are using hacks.

Not only was there star hacks but there was the older and not much used underscore hack something like: _margin-left:20px; which again targets only anything older than MSIE 5, which is pretty much pointless. Not only is it invalid according to W3C, but it’s also outdated.

First job, strip out all of the invalid code and move to a new CSS file. Fix all 39 other validation errors first and get it valid according to W3C, then recheck to see if the hacks are needed.

If you are at all interested in Web Standards then valid code should be one of your top priorities, this might mean spending several hours going though the code line by line to fix some errors left behind by junior members of the team, but in the end it might save some time in downloading the content and be more readable for editing later on. Once your CSS validates, then look to see what needs hacking further to look good in IE, but what you must do is put the IE specific CSS in its own stylesheet.

Why use conditional stylesheets?

  • You got problems, they need fixing’
  • Keeps your code hack-free and valid
  • Keeps your main stylesheet clean
  • Perfectly acceptable technique, sanctioned by Microsoft

So if you want to add in some IE only stylesheets just add this simple bit of code below into the of your document next to your other CSS call.

Target ALL VERSIONS of IE

<!--[if IE]>         <link rel="stylesheet" type="text/css" href="all-ie-only.css" /> <![endif]-->

Remember kids, Hacks are dirty and should not be used unless you really have to, otherwise just use a separate CSS stylesheet and you will create valid CSS every time. Providing you code it properly and always validate your code.

Advertisements