Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

How to enhance your navigation with CSS

You can use CSS to modify a navigational element to indicate which page a user is currently visiting.

Websites generally use a navigation system to help visitors find their way around the site. This image shows a navigational system (left nav):

Screenshot of a typical left nav

As shown in this image, the left nav’s Slide Show link is dark indicating that the user is currently on the slide show page. This can, of course, be done using JavaScript but it can also be done using pure CSS, as described next.

Consider a website consisting of three pages, default.html, slideShow.html, and contact.html with an associated top nav, as shown here:

Screenshot of demo 3 page site with top nav

To use CSS to color the homepage’s Home nav link black only when a user is on the homepage, we use the following technique:

  • Let the homepage's <body> element be:
    
    <body id="home">
    
    
  • Let all <a> elements in the nav (for the entire site) that point to the homepage be:
    
    <a id="a_home" href="default.html">Home</a>
    
    
  • Let the linked to stylesheet have the following rule:
    
    body#home a#a_home {
      color: black;
    }
    
    

    This rule colors <a id="a_home"> black on any page whose body element is <body id="home">. Because there is only one such page, this rule colors the Home nav link black only when the user is on the homepage.

To see this technique used in this three page site, click CSS Nav. To view the associated source in Windows Internet Explorer, right-click a page and choose View source. For convenience, the contents of the associated CSS file, default.css, is copied here:


html, body {
  margin: 0; /* This can vary from browser to browser, so explicitly set it. */
  padding: 0; /* This can vary from browser to browser, so explicitly set it. */
}

body {
  padding: 0 1em;
}

ul#nav a {
  text-decoration: none;
  color: grey;
}

ul#nav a:hover {
  font-weight: bold;
}

body#home ul#nav a#a_home {
  color: black;
  font-weight: normal;
}

body#slideShow ul#nav a#a_slideShow {
  color: black;
  font-weight: normal;  
}

body#contact ul#nav a#a_contact {
  color: black;
  font-weight: normal;  
}

If you want to extend this core concept to larger sites containing sections, this example code:


<body class=”portfolioSection” id=”portfolioSection_thumbnails”>

might indicate that the user is in the portfolio section of the site on that section’s thumbnails page. This class and id information might be used, in conjunction with CSS, JavaScript, or both, to implement a nav such that when a user clicks a link to a site section, all that section’s sub-links become visible.

Related topics

CSS3
Internet Explorer 9 Samples and Tutorials

 

 

Show:
© 2014 Microsoft