Get specific with CSS by using body_class()

Standard

body_class() is a template tag that can be a very useful tool to target content on specific pages.

How it works

Adding it to a theme is pretty easy. In header.php it goes along with the <body> tag thusly:

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

and it outputs something like this (depending on what page you are viewing):

<body class="home blog">

…and the output changes to indicate if you are on pages, posts, archives, etc.

How This is Useful

Let’s say the text on your site is black, but you want it to be blue on just the home page. By adding body_class() you can target your home page, and your CSS will look something like this:

body {
color: black;
}

body.home {
color: blue;
}

Of course, there are many other (more useful) applications for this tool. It can also help out when writing jQuery scripts that use CSS classes to perform actions.

Other Helps

Here is a list of possible classes output by body_class().

If you want to do the same thing but with posts instead of your whole body, you can use post_class().

body_class() is great for CSS and jQuery, but if you are trying to target your home page in PHP, you can use is_home()… but that’s information for another post.