This is YetAnother blog on drop down menus. What I hope to achieve is a step by step approach with the minimal amount code for cross browser compatability.
This code is what I have distilled from many other web developers. Any web search will bring you many examples of drop down menus with CSS. The most popular is from A List Apart Suckerfish, 2003! and still people are getting this wrong.
- HTML
- CSS
- Javascript (fix for IE6)
1. Drop Down HTML
First we need a basic list. I have given this one an id of nav. Please note, for the nested lists, they need to be within the parent ‹li›.
2. Drop Down CSS
Try this css out yourself, change some things and see how it responds.
The main changes would be the font-size: 1em; and padding: 0.5em 20px; on #nav a: This is how big the navigation buttons are.
This will then have an effect on the top: 2.3em; of #nav ul This is how far down the drop down menu starts.
Finally the width: 14em; This is how wide the drop down menu will be. Use this to fit your longest menu name.
#nav, #nav ul { margin:0; padding:0; list-style-type:none; list-style-position:outside; position:relative; }
#nav a:link, #nav a:active, #nav a:visited { display: block; padding: 0.5em 20px; font-weight: bold; font-size: 1em; border-right: 1px solid #000; border-bottom: 1px solid #000; color: #a9a9a9; text-decoration: none; background-color:#424242; }
#nav a:hover { background-color: #b03328; color: #FFF; }
#nav li { float: left; position: relative; }
#nav ul { position: absolute; width: 14em; top: 2.3em; display: none; }
#nav li ul a { width: 14em; float: left; }
#nav ul ul { top: auto; }
#nav li ul ul { left: 14em; margin: 0 0 0 10px; }
#nav li:hover ul, #nav li.ie6hover ul { display:none; }
#nav li:hover ul, #nav li li:hover ul ,#nav li.ie6hover ul, #nav li li.ie6hover ul { display:block; }
3. Javascript (fix for IE6)
To optionally support IE6 you need to add some javascript to make IE6 respond to a:hover in the way modern browsers do.
ie6hover = function()
{
var nav_lis = document.getElementById("nav").getElementsByTagName("li");
for (var i = 0; i < navlis.length; i++)
{
nav_lis[i].onmouseover=function()
{
this.className+=" ie6hover";
}
nav_lis[i].onmouseout=function()
{
this.className=this.className.replace(new RegExp(" ie6hover\\b"), "");
}
}
}
if (window.attachEvent)
{
window.attachEvent("onload", ie6hover);
}
To include this code create a javascript file, drop_down_ie6_fix.js and in your head tag include it with something like this:
There you have it, simple and easy for smooth cross browser functionality. I have tested in IE6, IE7, IE8, FireFox, Safari and Chrome.



