Saturday, October 2, 2010

Targeting other browser in Css

Generally, targeting browsers other than Internet Explorer is unnecessary. All other currently
shipping browsers are pretty well behaved. However, under extreme circumstances,
there are exceptions. For users who still have to deal with Internet Explorer for Mac, you
can create overrides by importing a style sheet via a style element, but omitting url and
leaving no space between @import and the opening bracket:
<style type="text/css" media="screen">
/* <![CDATA[ */
@import("ie-mac-hacks.css");
/* ]]> */
</style>
This can be placed in the same style element as the import line for the clean style sheet:
<style type="text/css" media="screen">
/* <![CDATA[ */
@import url(clean.css);
@import("ie-mac-hacks.css");
/* ]]> */
</style>
For any other overrides, you need to resort to JavaScript, which isn’t an ideal solution—
after all, there are still plenty of people out there who routinely turn off JavaScript—but
it’s the best we’ve got.

For targeting a specific platform, you can use a script like this, added to an external
JavaScript file:
if (navigator.platform.indexOf('Mac')!= -1) {
var cssNode = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'mac-hacks.css');
document.getElementsByTagName('head')[0].appendChild(cssNode);
}
In this case, if the user has a Mac, the style sheet mac-hacks.css will be linked to, but if
the user has a different operating system, it won’t. (Win and Linux are values for other
popular operating systems that you may wish to target.)
To target specific browsers, use the following code block, replacing BrowserName with
Firefox, IE (for Internet Explorer, although conditional comments are a better bet for
dealing with IE issues), Mozilla, Netscape, OmniWeb, Opera, or Safari. Obviously, you also
need to change the file name of the CSS document in the href line, too, from
hacks-file.css to the relevant CSS document for your chosen browser in the first line of
the script.
if (navigator.userAgent.indexOf('BrowserName')!= -1) {
var cssNode = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'hacks-file.css');
document.getElementsByTagName('head')[0].appendChild(cssNode);
}

No comments:

Post a Comment