A useful CSS tip

Internet / Web related innovations
  • Ads

A useful CSS tip

Postby MikeAlx » Wed Sep 01, 2010 10:10 pm

Here's a useful CSS tip I picked up recently. One of those things that seems really simple once you know it - but I'd never thought of it!

The problem.

Say you have a menu (ie list of links) common to several web pages, and you want to highlight the link for the currently-viewed page, (eg by colouring it red rather than black). What I used to do was tag the selected link in the html with a special class called something like 'sel', eg:
Code: Select all
<li><a href='home.html'>Home</a></li>
<li><a href='articles.html'>Articles</a></li>
<li><a href='reviews.html' class='sel'>Reviews</a></li>

Now the problem with this is that the html has to be different for each page, so you can't use a server-side include and common link file without a fair bit of fudging.

The Solution
Instead of tagging the selected link, you can add an id tag to the document body to identify the current page. Then add the relevant matching tags as classes to the link items. Finally, use css to set a highlighting style when the body.id and link.class tags match. eg use html code:
Code: Select all
<body id='reviews'>
<li class='home'><a href='home.html'>Home</a></li>
<li class='articles'><a href='articles.html'>Articles</a></li>
<li class='reviews'><a href='reviews.html' class='sel'>Reviews</a></li>

and css code:
Code: Select all
/* Ordinary links */
body ul li a { color: #000000; }
/* Selected links */
body#home ul li.home a,
body#articles ul li.articles a,
body#reviews ul li.reviews a {
  color: #ff0000;

Obviously there's a slight overhead in css code, especially for a large number of links, but on the plus side, the html code for the links is identical on every page, so you can include it from a single html file.
Posts: 7
Joined: Tue Nov 03, 2009 7:12 pm

  • Ads

Return to Internet / Web