Wednesday, December 3, 2008

Conditional CSS

Even though CSS is a standard, there are differences in how web browsers render and support CSS. By far the biggest deviant is IE6, which has the poorest compliance of the major browsers I support (FireFox, IE, Safari). In some cases you can simply tolerate the differences, but more often than not you have to find workarounds to convince the non-compliant browser to do what you want. I generally target FireFox first to get what I want (because it has good standard compliance and has FireBug) and then tweak the CSS to workaround IE issues. Following are two methods to conditionally include CSS depending on the target browser. CSS Hacks The first method is to exploit CSS parsing bugs in browsers (mainly IE) to accept or ignore CSS attributes. This is often called CSS hacking. Although commonly used, it is not recommended [1,2]. Two common hacks prefix CSS attributes with a special character to select browser and browser version: *attribute -- for IE 7 and below (I haven't tested on IE 8) _attribute -- only IE 6 and below attribute -- all other browsers Example: div { *width: 20px; _width: 20px; } Conditional Comments The second method is to use conditional comments [1,2]. This relies on a feature in IE to conditionally include HTML and CSS content using special commands embedded in comments. This is the recommend method because it does not depend on bugs to work. However, it is not as tidy or simple to use as CSS hacks and it can't be used for other browsers. Furthermore, it relies on modifying the HTML source to work. The following example includes the CSS resource file main.css if the browser is IE 6. <!--[if IE 6]> <link rel="stylesheet" type="text/css" href="main.css" /> <![end if]--> You can also use comparators such as lt and gt. This example only includes the CSS file if the browser is IE 7 or less. <!--[if lte IE 7]> <link rel="stylesheet" type="text/css" href="main.css" /> <![end if]--> References [1] http://www.javascriptkit.com/dhtmltutors/csshacks.shtml [2] http://www.quirksmode.org/css/condcom.html