[ Team LiB ] Previous Section Next Section

11.5 Importing Browser- or Operating System-Specific Style Sheets

NN 4, IE 4

11.5.1 Problem

You want to load separate external style sheet files for users on different kinds of computers.

11.5.2 Solution

Use JavaScript to write <link> tags within the head portion of the page, branching according to operating-system detection. The following example loads different style sheet files for Mac users and all other users:

<script language="JavaScript" type="text/javascript">
var cssFile = (navigator.userAgent.indexOf("Mac") != -1) ? 
    "styles/macCSS.css" : "styles/pcCSS.css";
document.write("<link rel='stylesheet' type='text/css' href='" + cssFile + "'>");

You can combine the browser- or operating system-specific external style sheets with other fixed <link> elements in the same page, as well as other kinds of style sheet definitions or @import rules (where supported). If your content observes the strict version of XHTML, and you want dynamically generated code to also be in that form, you can use the following document.write( ) call instead:

document.write("<link rel='stylesheet' type='text/css' href='" + cssFile + "' />");

To simplify the validation of your script under strict XHTML, you can move the CSS file loading statements to an external .js file.

11.5.3 Discussion

Employing multiple style sheets for different browsers or operating systems imposes the same maintenance headaches as multiple page implementations for different browsers. Any change you make to the design needs to be adapted for each version and tested thoroughly on the designated platforms. And yet, some applications of CSS styles may create an imperative for separate style sheet rules for Internet Explorer for Windows versions that are not fully CSS-compatible (see Recipe 11.13).

11.5.4 See Also

Recipe 11.13 about the impact on IE 6 for Windows by CSS-compatibility mode; Recipe 5.5 for detecting the browser's operating system.

    [ Team LiB ] Previous Section Next Section