Add web browser type class to the body tag of your WordPress theme

Often you run into CSS issues with different browsers, and one way to easily make browser-specific CSS is if you have a browser class added to the body tag of your theme. That way you can for example just add .ie8 .myclass { cssfix } to specify CSS that will only be read by a certain browser (IE8 in this case).

Add this to your theme’s functions.php:

/*  Browser detection body_class() output
/* ------------------------------------ */	
function alx_browser_body_class( $classes ) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

	if($is_lynx) $classes[] = 'lynx';
	elseif($is_gecko) $classes[] = 'gecko';
	elseif($is_opera) $classes[] = 'opera';
	elseif($is_NS4) $classes[] = 'ns4';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) {
		$browser = $_SERVER['HTTP_USER_AGENT'];
		$browser = substr( "$browser", 25, 8);
		if ($browser == "MSIE 7.0"  ) {
			$classes[] = 'ie7';
			$classes[] = 'ie';
		} elseif ($browser == "MSIE 6.0" ) {
			$classes[] = 'ie6';
			$classes[] = 'ie';
		} elseif ($browser == "MSIE 8.0" ) {
			$classes[] = 'ie8';
			$classes[] = 'ie';
		} elseif ($browser == "MSIE 9.0" ) {
			$classes[] = 'ie9';
			$classes[] = 'ie';
		} else {
			$classes[] = 'ie';
		}
	}
	else $classes[] = 'unknown';

	if( $is_iphone ) $classes[] = 'iphone';

	return $classes;
}
add_filter( 'body_class', 'alx_browser_body_class' );

And there you go! Gecko is firefox by the way. As long as you use the following in your header.php, it will add the classes:

<body <?php body_class(); ?>>

No need for conditional tags on the html tag, so we keep header.php neat and tidy!

Written by:Alexander Agnarson

3 Responses

  1. jerry says:

    can I use this script in Joomla CMS website?

  2. desti says:

    Thank you for the explanation, I build a WordPress now. this useful.

  3. This is actually really helpful, thank you. But, I’ve tried it on opera (latest 20.0) and it actually adds “chrome” instead of the “opera” class, any ideas? Safari on the other hand only works if I disable the W3 total caching.

    Works fine on Firefox (changed gecko to ff), as well as chrome. You can check my site if you want to see it live, thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *