How to do a menu with sub items using CSS
on Saturday, November 1st, 2008 at 12:54 amEvery website needs a menu, in this tutorial i am gonna show you how to do a menu with sub items using only CSS and javascript.
First lets take a look at the final result:

The CSS
margin:0;
padding:0;
border:0;
}
.nav{
background: url(../images/nav-bar.gif) no-repeat 0 18px;
width: 934px;
height: 30px;
margin: 0 auto;
list-style: none;
font-size: 14px;
padding-left: 5px;
line-height: 15px;
margin-bottom: -8px;
position: relative;
padding-top: 18px;
}
.nav li{
display: inline;
line-height: 30px;
height: 30px;
float: left;
padding-bottom: 5px;
margin-bottom: -5px;
}
.nav li a{
color: #fff;
float: left;
height: 30px;
padding: 0 19px;
text-decoration:none;
}
.nav li a:hover,
.nav li:hover a,
.nav li.hover a{
background: url(../images/hover.gif) repeat-x;
text-decoration: none;
}
.nav li ul{
background: url(../images/1×1.gif);
display: none;
}
.nav li:hover,
.nav li.hover{position: relative;}
.nav li:hover ul,
.nav li.hover ul{display: block;}
.nav li ul{
width: 125px;
position: absolute;
top: 31px;
left: 0px;
}
.nav li li{
background: #5a8a47;
display: block;
float: none;
height: auto;
font-size: 12px;
line-height: 14px;
padding: 4px 0 3px 18px;
margin-bottom: 1px;
}
.nav li li a{
float: none;
padding: 0;
}
.nav li:hover li a,
.nav li.hover li a{background: none;}
.nav li li a:hover{
background: none;
text-decoration: underline;
}
Defining “html,body,ul,li” to avoid any not desired margin, padding and border.
Class “nav” is for the whole “ul”, of course you can change the width (so background pic) to suit your needs.
You can easily figure out your way in the rest
The Javascript
var nav = document.getElementById(“nav”);
if(nav){
var nodes = nav.getElementsByTagName(“li”)
for (var i=0; i
this.className+=" hover";
}
nodes[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" hover\\b"), "");
}
}
}
}
if (window.attachEvent) window.attachEvent("onload", hover);
The javascript here is responsible for the rollover menus, all it does really is add the “hover” class to an “li” element on mouseover and replace it with “” on mouseout.
Hope this is useful, you can download the files from http://mazesolutions.me/demos/hmenu/hmenu.tar
Demo: 
// Jo
3 Comments »
[...] last CSS tutorial i wrote was about making a two level menu using CSS/JS, well this one is about fixed [...]
[...] last CSS tutorial i wrote was about making a two level menu using CSS/JS, well this one is about fixed footers… You know how it is ! you just wanna keep this [...]
RSS feed for comments on this post. TrackBack URL