A question I often receive is what's the best way to implement a multi-level navigation bar for a website. In some cases, some of my readers ask to me a little help and send me "very original" solutions but not so suitable in terms of semantic and unobtrusive approach to coding. For my experience, I always suggest to use simple and standard methods. So in this tutorial I want to illustrate you how to implement a perfect multi-level navigation bar using HTML, CSS and some lines of unobtrusive JavaScript code with jQuery to show and hide sub sections. The result is the following:

You can quickly reuse the code I provided in this tutorial into your web projects, customizing the CSS file and changing the links. You can take a look at the demo here or download the source code here.

Navigation bar structureHere is the standard box model of a typical navigation bar:

...and here is the standard HTML structure you would have to use to implement it

<div id="nav"><!-- nav container -->

<ul>

<li>item <!-- main item -->

<ul><!-- item submenu -->

<li>sub item</li>

</ul>

</li>

<ul>

</div>

How you can see the code is composed by some nested unordered list. For example, in this tutorial I used the following code (main navigation items highlighted in bold):

You can add new main items or sub items simply adding new <li> tags with an <ul> tag within.

CSS CodeNow take a look at the CSS code. I prepared a very basic style you can customize how you prefer in your projects. Here is the code for the container of the navigation bar (<div id="#nav">):

#nav{

height:32px;line-height:32px;background:#3B5998;padding:0 10px;}

#nav ul, #nav ul li {

margin:0;padding:0;list-style:none;

} #nav ul li{

float:left;display:block;

}

Here is the code for navigation links. #nav ul li {...} it's the code that defines main items (in this tutorial for example they are Web Design, Tech News, Social Network). #nav ul li ul li {...} it's the code that defines sub items for each main item.

jQuery CodeNow take a look at this simple jQuery code that shows and hides sub sections using mouseover and mouseleave jQuery events. The code is very simple and works independently from the number of main items contained into the navigation bar. You have to copy the following code into the <head> tag of your page. Remember first to include a link to jQuery using the following code:

<script type="text/javascript"src="jquery.js"></script>

Than add this code:

<script type="text/javascript">function nav(){

$('div#nav ul li').mouseover(function() {

$(this).find('ul:first').show();

});

$('div#nav ul li').mouseleave(function() {

$('div#nav ul li ul').hide();

});

$('div#nav ul li ul').mouseleave(function() {

$('div#nav ul li ul').hide();;

});

};

$(document).ready(function() {

nav();

});</script>

You can also add this code in an external JS file and import it into the page that use this script. That's all! Take a look at the demo here or download the source code here.