I have been wanting to write a CSS post for a while now, so I thought CSS hacks would be a good topic. By now, I think everybody knows that using CSS hacks is not a good thing, or at least I hope they do !
A method that I have seen gaining popularity over the last few years was to add a CSS class for IE browsers to the HTML tag.
I totally agree with this method, however I have personally been taking this method a step further for a long time now and use it for all browsers, not just IE.
If you are using PHP, you can do the following:
function getBrowserUACSS() {
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('/linux/i', $ua)) {
$platform = 'linux';
}
else if (preg_match('/macintosh|mac os x/i', $ua)) {
$platform = 'mac';
}
else if (preg_match('/windows|win32/i', $ua)) {
$platform = 'windows';
}
// browsers to sniff and the css class name to give them
// yes browser sniffing sucks, but it will do for now
$browsers = array(
'chrome' => 'chrome',
'safari' => 'safari',
'opera' => 'opera',
'msie' => 'ie',
'firefox' => 'ff'
);
$browser_css_string = '';
foreach ($browsers as $browser => $css_class) {
if (preg_match('#(?' . $browser .')[/ ]+(?[0-9]+(?))#', $ua, $version)) {
$browser_css_string = $platform . ' ' . $css_class . ' ' . $css_class . '_v' .$version[2];
break;
}
}
return $browser_css_string;
}
?>
From the example above, I can target virtually all browsers on all platforms using a single stylesheet and individual css classes.
// all IE browsers
.ie {}
// IE6 only
.ie_v6 {}
// IE6 and IE7 only
.ie_v6, .ie_v7 {}
// all Firefox browsers
.ff {}
// Chrome 17 only on Mac
.mac.chrome_v17 {}
// etc...
As you can see, it’s a lot better than using hacks or multiple stylesheets, and you can target any browser running on any platform.