Changing Backgrounds with body class()

The body_class() WordPress function attaches a list of classes to the <body> element according to what type of page is being displayed.

These classes can be used — in conjunction with your theme’s stylesheet — to display different backgrounds on different pages.

Let’s assume your header.php template file contains:

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

And your current CSS for the background looks like:

body {background:#fff url(images/bg.jpg);}

 

In a single post, your body tag would look like:

postid-188 single-format-standard logged-in admin-bar">

A category page could have:

<body class="archive category category-cat-a category-9 logged-in admin-bar">

whilst a tag page might generate:

tag-tag1 tag-92 logged-in admin-bar">

The CSS

You can add some new rules to your theme’s CSS to target specific backgrounds at particular pages.

Default Single Post

body.single {background:#ccc url(images/bg-single.jpg);}

Single Post with an ID of 188

body.postid-188 {background:#999 url(images/bg-special.jpg);}

Default Category Background

body.category {background:#eee url(images/bg-cat.jpg);}

Category A Only

body.category-cat-a {background:#ddd url(images/bg-cat-a.jpg);}

The possibilities are almost endless.

You can find a full list of the classes generated by the body_class() function in the WordPress Codex.

  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: