Skip to content

Pure CSS method to indicate the page you are on

Posted on 26 March 2006

The idea of this method is to allow you to target a specific navigation item with css.

You must place a unique id on the body of each page in your site and a unique id on each navigation element. With the combination of body id and navigation id you can style accordingly in your css.

The best way to understand it is by example. If my markup looks something like:


<body id="body_home">

<ul>
  <li><a href="/" id="nav_home">Home</li>
  <li><a href="about.php" id="nav_about">About</li>
</ul>

Then my CSS would be as simple as:


#body_home #nav_home, #body_about #nav_about{
 color:red;
}

Obviously the actual styling doesn't matter, but you get the idea. Where the body id indicates the page is home then I style the home nav element accordingly, the same with about etc. etc.

How does it work with sub navigation?

Now to take this a step further you may want to consider the situation where you have sub navigation elements. So you need to style the main navigation to indicate the section you are in, and then style a sub nav element to indicate the particular page you are on.

In this situation I style the main navigation elements with classes on the body rather than with an id. Every page within a section will have that same class on the body to ensure it has the correct main navigation element highlighted.

So every page still has it's own unique body id that is used for styling the sub navigational elements. I'll show you with another example:


<body id="body_news_archive" class="news">

<ul>
  <li><a href="/" id="nav_home">Home</li>
  <li><a href="about.php" id="nav_about">About</li>
  <li><a href="news.php" id="nav_news">News</li>
</ul>

<ul>
  <li><a href="news.php" id="nav_news_archive">News Archive</li>
</ul>

Then my css would be as follows:


body.home #nav_home, body.about #nav_about, body.news #nav_news{
 color:red;
}

#body_news_archive #nav_news_archive{
 color:blue;
}

View the snippets archive ››

No comments have been left

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com