SEARCH HYPERTRANSITORY

JG ON THE WEB

Targeting the BODY tag with CSS in WordPress

I recently had cause to resort to an old trick to target a single page with CSS.

It turned out to be a bit of an ordeal in WordPress, although I must admit it’s still easier than in Joomla.

Anyway, it’s important to be able to get to that “body” tag so you can attach a CSS ID or Class to it in order to specifically target only that one page.

Being able to do this is a huge boon since it eliminates the need for using page specific styles in the “head” section of your page, which was the method I learned when I was first learning CSS.

Unfortunately, though, with the advent of the Content Management Era, it can be more and more difficult to actually get access to that body tag on a “per page” basis. Depending on your CMS software, how a “page” is generated can be twitchy.

In Joomla it’s tough to do, and most times requires a bit of php script to get it done. I’ve used it before but I don’t like to leave rogue scripts in my sites that I might forget about later. The main reason I hate to do it because it’s a workaround, and I hate workarounds for things that I feel should be built into the software.

So, back to WordPress, though. I hunted around for quite awhile for some sort of plugin or code that I could use to add a class or ID to the body tag “on the fly”, meaning that I would want the ID of the body to be pulled from the specific page name or ID or post ID or something that I could hook onto and use for a specific style on that one page.

As it turns out, I should have started at the WordPress Codex, since there was a perfectly good body class template tag sitting right there.

Long story short, you go to your wp-content>themes>YOUR-THEME-NAME>header.php file, then find the body tag and plunk in this code:

So it’s a bit of overkill, but you can be pretty sure there will be something for you to hook onto.

And that should help out just in case you need to do some page specific CSS wrangling. I wish I would have found this before I did an hour of searching on this.

Oh well, next time I’ll remember to start at the official documentation and work my way out from there.

To wrap up, these CMS’s really need to do a better job of allowing access to certain tags right in the interface. As far as I’m concerned, whenever a CMS is going to generate a page, there should be a field there to put in the body ID, and right under that there should be one to put in the body Class, too. Make it happen, people.

SEARCH HYPERTRANSITORY

JG ON THE WEB

5 thoughts on “Targeting the BODY tag with CSS in WordPress”

This is a great post!! WordPress is my favorite CMS (as you know! :) we’ve had this discussion before…) and I use it for probably 90% of the sites I design but I did not know about this little trick…very handy! I’ve never had to use different body classes which is why I’ve never thought about it, but I am going to have to start now… :)