Use A Body ID To Style Your Website In CSS

Trevor Davis wrote a convincing article why using ID’s in the body tag makes sense. I often use it to keep different page layouts sorted and inserted an id manually. Now he shows an interesting way using PHP and/or Wordpress. Check out the demo.

css
Creative Commons License photo credit: Raphael Goetter

Reasons to use id’s in Body

  • Maybe your design has different colors depending upon which section you are in. Instead of having to touch the markup, you can just modify the CSS depending upon the id on the body.
  • You can control the current states for your navigation.
  • Maybe the markup on your homepage is a little different than subpages, so instead of creating a different template, just stick in an if statement.

Example

Body


<body id="<?=$bodyId; ?>">

Function


<?php

function exampleSetBodyId() {

$path = $_SERVER['REQUEST_URI'];
if(!isset($bodyId)) {

if(eregi('^/play/set-a-body-id/about/',$path) == 1) {

$bodyId = 'about';

} else if(eregi('^/play/set-a-body-id/blog/',$path) == 1) {

$bodyId = 'blog';

} else if(eregi('^/play/set-a-body-id/contact/',$path) == 1) {

$bodyId = 'contact';

} else if(eregi('^/play/set-a-body-id/work/',$path) == 1) {

$bodyId = 'work';

} else if(eregi('^/play/set-a-body-id/play/',$path) == 1) {

$bodyId = 'play';

} else if ($path == '/play/set-a-body-id/') {

$bodyId = 'home';

} else {

$bodyId = 'general';

}

}
return $bodyId;

}

$bodyId = exampleSetBodyId();

?>

Spread the words

Digg Del.icio.us Stumble Float Technorati Bump
Leave a comment!
Note: You can also use your free Gravatar avatar on Knowtebook! Please also read our Publishing Policy before posting.

Yes, I would like to receive notification on incoming comments!