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

Go to source

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!