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 '<body class="chrome">';
	} else {
		echo '<body class="safari">';
	}
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
	echo '<body class="opera">';
} else {
	echo '<body>';
}

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.

10 thoughts on “CSS: How to write CSS rules to detect or target Chrome, Safari or Opera browsers only?”

  1. This is great!
    In my project, I wanted to find browsers that support both @font-family (download font) and support for Open Type ligatures, so I did the following. This may be good just to limit your page to one set of browsers:
    ==============CODE SAMPLE==================

    I like this browser!

    Uh, oh. Maybe you should get one of these:
    Firefox, Safari, Lunascape or Arora.

    ==============END CODE SAMPLE==============

  2. You should rarely need to do this as you can code for chrome and have alternative stylesheets for ie and special coding for FF. @santosh, you can do this using the author’s technique, and when the browser matches chrome just output a javascript alert()

Comments are closed.

Scroll to Top