This Short Version
Add a class attribute to your
tag for each part of the page’s path in the URL. E.g.: The page http://example.com/about/history should have a body tag that looks like<body class="about history">
. It makes styling those sections of your site nice and simple.
The Explanation
Often times, specific styling/formatting is shared between similar pages. The traditional way to deal with this is to include additional CSS files when special formatting is needed. I’ve found body classing to be more useful and more efficient.1
Since the pages that share styling often also share a path in the url, it’s really simple to add the path parts as classes to the body tag. For example, say the about section of a web site needs special formatting because it has an extra sidebar or maybe some sort of widget. I would add the class ‘about’ to the body tag of all of the about pages. This method continues down the hierarchy. The page at /about/history would have a body class of ‘about history’, and so on. It’s very simple and very handy.
It’s also very simple to add this functionality to your layouts whether you’re using Rails or any other framework. My PHP framework, Phooey, does it for you automatically.
For Rails, you can include this in your layout:
<body class="<%= controller_name -%> <%= action_name -%>">
…or, if you’re using Haml (which I highly recommend):
%body{:class => "#{controller_name} #{action_name}"}
Agree? Disagree? Confused? Let me know down there in the comments.
- I am of the opinion that you should only include one CSS file per media type in any page of your site (except for the IE stylesheets). I usually include only the following stylesheets in every page of every site: all.css, screen.css, print.css. And each one of those is minified. More on this in my forthcoming article on Sass. ↑ back up there
Oct 22nd, 2009 at 11:49 pm james
using class tags on your body is pretty cool, and allows you to let css do the work for detecting current page styles on menu items. A really lazy way so you dont have to do any server-side processing to add a class=”current” to menu items and can thus include a “static” tpl file with your main menu once.
.history a#history, .about a#about, .faq a#faq { background-color:pink; /* make the current page stand out */ }
about history faq
Jan 16th, 2011 at 10:07 am Ben
Nice tip. One thing I was wondering - how does the minus symbol impact on the output?
I.e. any reason why not to just put:
Jan 16th, 2011 at 10:10 am Ben
Code didn’t appear in my comment. 2nd attempt:
(minus characters removed)
Jan 16th, 2011 at 11:31 am Jason Johnson
Ben, sorry your code is not coming through. Markdown must be having an issue. The dashes on the closing erb tags prevent a newline after the code. It’s not required.
Jan 19th, 2011 at 9:48 am Ben
Thanks, good to know. I did try to Google “-%>” but it’s futile :)