Monday, November 28, 2011

CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only?

It’s easy to target firefox, just write as expected by the standards, at least most of the time. It’s also easy to target IE and any specific versions of them by a few of the famous hacks or the IE conditional comments to selectively include style sheets by version numbers. But how does one write CSS rules and make the browsers to recognize that they are particularly for Chrome, Safari or Opera?

Use PHP to distinguish the browsers.

echo $_SERVER['HTTP_USER_AGENT'];

Put this line in a .php file, upload the file to your server and browse to it by all the different browsers you have. From the server side, $_SERVER['HTTP_USER_AGENT'] contains all the information PHP knows about the source of the request, namely your browser. Now that the server is able to recognize the client browser, you can serve up different versions of a web page by PHP and include different CSS classes according to the browser type:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false) {
// Chrome user agent string contains both 'Chrome' and 'Safari'
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
echo '';
} else {
echo '';
}
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
echo '';
} else {
echo '';
}

The rest is very simple. Just cascade your styles by additional classes to adapt your design to Safari, Chrome or Opera specifically. You can do a lot more than this by the server side variable $_SERVER['HTTP_USER_AGENT'], such as detecting browser versions and operating systems or writing your own web traffic statistics software.

No comments:

Post a Comment