Add unique styles to your pages using the body_class() function

When WordPress 2.8 was released, a new function called body_class() was made available to developers allowing us to style our pages differently. This new function places a location-specific class on the opening <body> tag. I must admit, I missed this function when it came out and only discovered it recently. But it’s proved very useful. I can now specify different background images for my pages and posts.

Here’s how to do it.

Open up your header.php file and change <body> to <body <?php body_class(); ?>>

The function will automatically generate extra html code. Have a look at the source code to see what classes are available to you and simply create new styles.

For example if you have an about page which has a page id equal to 2, you will notice the following code:

<body class="page page-id-2">

In your css, you could add a new style such as

body.page {background:yellow;}

This would change the background of all your pages to yellow.

Or

body.page-id-2 {background:yellow;}

And now the yellow background will only be applied to the page with id #2.

Nathan Rice wrote up a great article about the body_class() function and you can, of course, get more information by visiting the Codex.