| home / experts / dhtml / diner / ssheets |
![]()
This is a DHTML cross-browser technique. The examples discussed will only work in Navigator 4 and Explorer 4, all platforms. |
Browser-specific Style Sheets (3)In this version of our technique, the Navigator styles are included first on the page, enclosed in a STYLE tag with the DISABLED property: <STYLE TYPE="text/css" DISABLED>
<!--
P.example {color:green}
-->
</STYLE>
Navigator gets its styling, and will not read another style sheet, since we will create the Explorer version dynamically. The createStyleSheet() methodExplorer 4 introduced the powerful, put seldom used, createStyleSheet() method of the document object: variableName = document.createStyleSheet(); This is, more or less, like writing the following HTML: <STYLE ID=variableName TYPE="text/css"></STYLE> In other words, it creates a style sheet with no rules. The addRule() methodEvery styleSheet object in Explorer has an addRule() method, enabling us to build the style rules, and populate the empty style sheet, on-the-fly: newSS = document.createStyleSheet();
newSS.addRule("P","color:maroon");
Notice that addRule() takes two arguments, the style selector, and style specification. In other words, the first argument is what usually exists outside the curly braces ({}), and the style specification is what we normally include inside the braces. Putting it TogetherNow, we can combine the STYLE and a SCRIPT for browser-specific styles. You can add as many rules as you like with the addRule() method. <STYLE TYPE="text/css" DISABLED>
<!-- /* Navigator will */
P.example {color:green} /* read this style sheet */
P.otherExample {font-size:10pt}
--> /* Explorer will ignore it */
</STYLE>
<SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!-- // only version 4 browsers read this script
if (document.all) { // only Explorer 4 can read the statements
newSS = document.createStyleSheet(); // create a style sheet
newSS.addRule("P.example","color:maroon"); // add a style rule
newSS.addRule("P.otherExample","font-size:12pt"); // and another one
}
//-->
</SCRIPT>
Pros and ConsIn this page's example, Navigator and Explorer read only the styles meant for them. Unfortunately, the style sheets are mutually exclusive, so a third style sheet is necessary for cross-browser styles. On the final page, we'll create an elegant method for importing browser-specific external style sheets. |
Produced by Peter Belesis and
All Rights Reserved. Legal Notices.
Created: Feb 09, 1999
Revised: Feb 09, 1999
URL: http://www.webreference.com/dhtml/diner/ssheets/ssheets3.html