Where to put your CSS hacks – conditioning your conditionals.

I’ve had/heard/seen this argument many times on blog after blog. So I thought it would be a useful blog post to highlight to upsides and down sides to each argument.

Conditional Comments

Conditional commenting is the practice of putting code in special comments in your HTML document that get executed only in specified IE browers, it usually looks something like this:

  • Pro’s

  • Keeps hacks separate making style sheet look clean.
  • Allows for automated validation of main style sheet
  • Enables clean easy use of completely browser specific enhancement code like filters and expressions
  • Is backwards compatible
  • Con’s

  • Encourages people to write browser specific CSS instead of writing better CSS. (broken windows theory)
  • Decoupling of styles can result in more bugs when people forget to update the conditional stylesheet. Also bugs can be harder to track down.
  • Is an extra HTTP request

Inline CSS Hacks

Inline CSS hacks are where you write *hacked* attribute, property pairs in your CSS using combinations of ascii characters to take advantage of bugs in different CSS parsers, looking something like this:

  • Pro’s

  • Keeps hacks together with real code for easier tracing/debugging.
  • Less likely duplication of code
  • Con’s

  • Encourages people to use hacks instead of writing better CSS. (broken windows theory)
  • Stops automated validation of CSS as hacks are in the core code.
  • Hacks can be unreliable and have adverse effects on different browsers other than the infamously un-robust IE family.
  • Is not backwards compatible, if a hack gets fixed the rendering will break on later browsers

Ultimately it’s a preference thing and you can spin these pro’s and con’s either way to support your chosen method of development, but once it’s been chosen all developers need to stick with it. I think the important thing is that everyone needs to be vigilant that both are used with extreme caution and care as a last last resort in the CSS.

I see two useful things that could be created to follow this up to create the desired behaviour:

  • setting up some code that analyses the amount of CSS versus the amount of hacks or conditionals, then having a theoretical limit say 5% that you are not allowed to go above for a successful build.
  • Having a rule to write a detailed reasoned 3 line discourse in comments giving a description of why and in what circumstance each hacked rule is required.

Personally I opt of the conditional method, but that’s because I have a bizarre obsession with automated validation of CSS. See CSSOrder.

Leave a Reply