emailGitHubLinkedIn

Setting the body element's id attribute to use page-specific CSS rules

Sometimes a web design requires CSS rules specific to a page. Perhaps you want to highlight the current page in the site navigation, or change the typography to match a page's theme. You could write a separate CSS file containing such rules for each page, but this can lead to writing the same or similar rules in multiple places, violating the DRY principle and making maintenance error-prone. Also, if your site has a lot of pages, or if one script can generate different pages depending on user input, creating CSS files with rules specific to each may be undesirable or impossible. But there's another way: setting the id attribute of the page's <body> element, and writing CSS rules specific to <body> elements with that id.

Doing so is pretty simple. In the markup of each page that needs specific styling, set the <body> element's id (or class) attribute to a unique value. Then, in a CSS style sheet used by all those pages, write the rules for each page, prefacing each rule's selector with body#id (or body.class). My portfolio site uses this technique to underline the current page's link in the main site navigation, using the following rule:

#nav a:hover, body.projectspage #nav ul li#projectslink {
	border-bottom: 3px solid #bdefbd;
}

This creates a border beneath the "Projects" link the same way as when a user hovers their mouse over any of the navigation links, but only when the <body>'s class is projectspage, which is true when one views a project's details. The same rule could be applied to further pages by adding body.pageclass #nav ul li#pagelink selectors to the rule. Keeping these rules together in a single file and applying them only for certain <body> classes reduces the number of pages of which I need to keep track and allows me to change the rule in one place yet keep it consistent across all pages.

If you're using my MVC framework for PHP and wish to use this technique, you can set the <body> element's id or class in MVC_PageView's constructor. Create an associative array with an element where the key is either 'id' or 'class' and the value is the page's unique id or class, then pass the array to the constructor's $bodyAttribs parameter.