Add the browser name and version to the body class

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!

Advertisements
About

Web Developer @ Oakwood Creative - www.oakwood.se

Tagged with: , ,
Posted in Beginner
2 comments on “Add the browser name and version to the body class
  1. Matthew says:

    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 )

Google+ photo

You are commenting using your Google+ 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 120 other followers

%d bloggers like this: