Tuesday, June 24, 2008

Show active links with CSS and 'includes'

A common practice in web design is to use 'includes' for repeating page elements - such as a navigation bar or a sidebar. I am sure all web application frameworks provide some way of using includes. What I could not figure out was a simple way of highlighting the active link in that include - short of scripting, or not using includes at all.

But then again - I hadn't googled it - and here is a simple, even though not the most elegant way of highlighting the active link: Called the Body ID/Class method.

http://www.websiteoptimization.com/speed/tweak/current/

The idea is to add a separate class to each <body> tag and use a corresponding class or id for the link to that page. For example if I add a class 'home' to the <body> tag on my home page, and an id 'home' to the <a> that links to the page in my navigation include,

I just need to add this CSS rule:

body.home a#home{style declaration}

I agree the addition of an extra class to the body tag may be a bit cumbersome - but if you can maintain separate title tags for all pages - you can also do that for your body tags - just follow some kind of standard naming convention.

The benefits to code brevity and code management are immense.

No comments: