Wouldn’t it be great if you can specify different styles per page all from the stylesheet? For example, your home page may have a larger header section than the rest of your pages. The solution would be to add a different class on each page so you can do something like this:

.header {
  height: 30px;
.home .header {
  height: 100px;

Only problem with this is most of the time your pages are generated by a content management system or web application. That means, you would have to hook into the page lifecycle and add the page name to the <html> or <body> tag. That seems like overkill. JavaScript to the rescue!

Page Name as Class

Add this in your startup script to add the page name to the <html> tag:

var file = window.location.pathname;
var index = file.lastIndexOf('/');
var page = index >= 0 ? file.substring(index + 1).toLowerCase() : '';
$(document.documentElement).addClass(page || 'home');

First it is getting the page name by finding the last segment of the URL. Then it goes to the root object (<html>) and adds the page name as a class to it. It defaults to ‘home’ if there is no page in the URL. Now each page will have its own specific class name!

<html class="home">

Page Title as Class

If the page file name is not enough for you as the class name, you can use the document title as the class name. That will give you more control over what class name is generated. It will need to be scrubbed from special characters though because there is a specification on what are valid class characters. Here’s how you would do that:

if (document.title)

In this case, it is checking if a page title even exists, then going to the root object (<html>) and adds the scubbed page title as a class to it. The magic ingredient here is underscore-string’s _.slugify function will will scrub the name for valid class names. It is a great plugin to the famous underscore.js project. It’s open source so you can steal the RegEx from the source code if you like.  Now each page will have the title as a class name.

This should make your graphic designers very happy ;)

NOTE: I recommend prefixing the class name with page-* to prevent conflicting with other class names.