WordPress Quick Tips

Add the browser name and version to the body class

Posted by: Vincent on: September 1, 2010

As suggested by Phil Irish, the best way to make browser specific CSS is with a class on the body element rather than separate CSS files or complex hacks.

In his example he used conditional HTML to create multiple body-tags, but with this simple function you can just add the browser name and version to the classes printed by WordPress’ body_class function.

function mytheme_body_class( $class ) {
 $arr = array(
 'msie',
 'firefox',
 'webkit',
 'opera'
 );
 $agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );

 foreach( $arr as $name ) {
 if( strpos( $agent, $name ) > -1 ) {
 $class[] = $name;

 preg_match( '/' . $name . '[\/|\s](\d)/i', $agent, $matches );
 if ( $matches[1] )
 $class[] = $name . '-' . $matches[1];

 return $class;
 }
 }

 return $class;
}
add_filter( 'body_class', 'mytheme_body_class' );

Modify the array if you want to sniff out even more browsers. Simple enough I think!

Tags: , ,

2 Responses to "Add the browser name and version to the body class"

An updated version of this function would need to use [0-9]+ instead of \d for browsers with multidigit version numbers such as IE 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

About

WordPress Quick Tips is a blog supplying great tips about WordPress.

We hope to create a great knowledge resource for WordPress developers as well as serving a reminder for all the forgetful ones.

The blog is created and run by Vincent of Oakwood Creative

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 86 other followers

Follow

Get every new post delivered to your Inbox.

Join 86 other followers