Home » CSS 3 » Active style for navigation

Active style for navigation

Active style for navigation

All websites highlight the navigation item of the user’s location in the website, to help users orientate themselves. This is a fundamental requirement for basic usability. To achieve this, most of the developers use ‘active’ class for link in each page. They will have to change the HTML code behind the navigation for each and every page. Otherwise developers use jquery for this purpose. Can we do it or possible to have the navigation highlighted on every page, without having to tweak the HTML code on each and every page? or without using jQuery. Of course it is possible…

First, I will give the HTML required for this. Then I can explain how to do.

HTML required for Active style for navigation

<ul>
<li><a href="#" class="home">Home</a></li>
<li><a href="#" class="about">About us</a></li>
<li><a href="#" class="services">Services</a></li>
<li><a href="#" class="contact">Contact us</a></li>
</ul>

Here I have assigned a class to each navigation item:

You’ll then need to insert an id into the <body> tag. The id should be representative of where users are in the site and should change when users move to a different site section. When in ‘Home’ it should read <body id=”home”>, in ‘About Us’ it should be <body id=”about”>, in ‘Services’ is should be <body id=”services”> and in ‘Contact Us’ <body id=”contact”>.

Next, you create a new CSS rule:

CSS required for Active style for navigation

#home .home, #about .about, #services .services, #contact .contact
{
background: red;
}

This basically creates a rule that only takes effect when class=”home” is contained within id=”home”, and when class=”about” is in id=”about” and class=”service” is in id=”service” and class=”contact” is in id=”contact”. These situations will only occur when the user is in the appropriate site section, seamlessly creating our highlighted navigation item. Note that this is useful when you are doing static website.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*