DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 3.12 Creating Contextual Menus

Problem

You have a navigation menu, created with Recipe 3.6. You want to highlight the current page's location on the menu, as in Figure 3-25.

Figure 3-25. The navigation set of links
figs/csscb_0325.gif


Solution

Place an id attribute in the body element of the web document:

<body id="pagespk">

Also, place id attributes in the anchor elements for each link in the menu:

<div id="navsite">
  <h5>Site navigation:</h5>
  <ul>
   <li><a href="/" id="linkhom">Home</a></li>
   <li><a href="/about/" id="linkabt">About</a></li> 
   <li><a href="/archives/" id="linkarh">Archives</a></li>
   <li><a href="/writing/" id="linkwri">Writing</a></li>
   <li><a href="/speaking/" id="linkspk">Speaking</a></li> 
   <li><a href="/contact/" id="linkcnt">Contact</a></li>
  </ul>
</div>

With CSS, place two id selectors into one descendent selector to finish the menu (see Figure 3-26):

#pagespk a#linkspk {
 border-left: 10px solid #f33;
 border-right: 1px solid #f66;
 border-bottom: 1px solid #f33; 
 background-color: #fcc; 
 color: #333; 
}

Figure 3-26. The current link is different from the rest of the links
figs/csscb_0326.gif


Discussion

If you have a small site, you can show a link in a set of navigation links representing the current page by stripping out the anchor link for that page:

<div id="navsite">
 <h5>Site navigation:</h5>
 <ul>
  <li><a href="/"Home</a></li>
  <li><a href="/about/">About</a></li> 
  <li><a href="/archives/">Archives</a></li>
  <li><a href="/writing/" >Writing</a></li>
  <li>Speaking</li> 
  <li><a href="/contact/" >Contact</a></li>
 </ul>
</div>

For larger sites that might contain secondary menus, stripping out the link tags on each page increases production and maintenance time. By marking up the links appropriately, the links can be called from a server-side include, and then you can edit the CSS rules that control the style of the navigation links as needed.

To expand the one CSS to include all the links in the navigation menu, group the descendent selectors by a comma and at least one space:

#pagehom a#linkhom:link,
#pageabt a#linkabt:link,
#pagearh a#linkarh:link,
#pagewri a#linkwri:link,
#pagespk a#linkspk:link,
#pagecnt a#linkcnt:link  {
 border-left: 10px solid #f33;
 border-right: 1px solid #f66;
 border-bottom: 1px solid #f33; 
 background-color: #fcc; 
 color: #333; 
}

In each web document, make sure to put the appropriate id attribute in the body element. For example, for the home or main page of the site, the body element is <body id="pagehom">.

See Also

The CSS 2.1 specification on descendent selectors at http://www.w3.org/TR/CSS21/selector.html#descendant-selectors.

    Previous Section  < Day Day Up >  Next Section