Clean CSS for Various Browsers with Conditional Comments

I was asked if I could explain a comment I left on 10 best CSS practices to improve your code on Webdesigner Depot some months ago.

The suggestion there was…

10. Keep a tidy house

Separate browser-specific CSS to its own individual style sheet, and include as needed with Javascript, server-side code or conditional comments. Use this method to avoid dirty CSS hacks in your main style sheets. This will keep your base CSS clean and manageable.

and I added…

I prefer to have all “browser tweaks” in the main CSS file, too. I use conditional comments to add a DIV around the whole page content identify IE browsers and then have…

.ie6 h1 {font-size: 20px} /* just an example */

… in the CSS file especially for IE6 tweaks.

Conditional comments allow you to have HTML in your page which is only visible to Internet Explorer or even only to Internet Explorer if it has a specific version.

By writing this you could load a CSS File only if the page is loaded in Internet Explorer 6:

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

So if you follow rule 10 on Webdesigner Depot, you end up having several different CSS files which have almost the same content. But that means, that if you change something, you’ll have to apply those changes to every CSS file – and if you forget one of the files, users with a specific browser version will get a broken layout.

My suggestion is to stay with just one (slightly bigger) CSS file and have all those minor browser tweaks in there – in a clean way, not with CSS hacks.

...

<!--[if lte IE 6]><div class="ie6"><![endif]-->
<!--[if IE 7]><div class="ie7"><![endif]-->
<!--[if IE 8]><div class="ie8"><![endif]-->
... do your html here
<!--[if IE 8]></div><![endif]-->
<!--[if IE 7]></div><![endif]-->
<!--[if lte IE 6]></div><![endif]-->


You’ll end up with a „full page container“ of the Internet Explorer version as class. Now, if you need some specific code for one version of IE, you can just say so in your CSS:

/* All other browsers */
div.box {height: 94px; width: 194px; padding: 2px; border: 1px solid red;}

/* Internet Explorer 6 */
.ie6 div.box {height: 100px; width: 200px; border: 1px solid green;}

Note that „padding: 2px“ is not overwritten and also applies to IE6. So if you decide to go to 3 pixels it’s just one location to change that.

There might be cases where you are better off with a seperate CSS for every browser – especially for pixel-exact designs. But in my experience it’s just small tweaks for old browser versions to fix major problems.

This approach has worked for me for some years now. Just give it a try and see yourself if you like it 🙂

(BTW: It would be nice to see some other browsers to support conditional comments, too. They are just „tweaks“, but they are quite helpful.)