Kriesi.at – new media design

Create a multilevel Dropdown menu with CSS and improve it via jQuery

Some of you might have noticed, I have a partiality for sleek menus. As I recently had to create a multi level dropdown menu for one of my customers, I wanted to improve it with a little bit of jQuery, but couldn't find a script that accomplished what I needed.

So I decided to build this menu from scratch and share my thoughts as well as the code with you.

So before we start: this is what we are going to build


The first part of this tutorial is dedicated to the task of building a working CSS-only dropdown menu (also known as suckerfish menu), the second part will show you how you can pimp the whole thing with a few lines of jQuery.

The CSS-only menu is cross browser tested and from what I can tell works with all browsers except for IE6.
The Internet Explorer needs the addition of our jQuery function to work properly.

To create a CSS-only dropdown menu that works without Javascript (even in IE6), you need tons of extra markup and CSS, if you really need this for any reason check out Stu Nicholls CSSplay, he addresses this problem with heavy (ab)use of conditional comments =)

Now that you have a little bit of background information, lets create our own menu:

First of all we need the XHTML Structure of our soon-to-be terrific menu. We will use a nested list for this purpose, top level list id is "nav":

<ul id="nav">
    <li><a href="#">1 HTML</a></li>
    <li><a href="#">2 CSS</a></li>
    <li><a href="#">3 Javascript</a>
        <ul>
            <li><a href="#">3.1 jQuery</a>
                <ul>
                    <li><a href="#">3.1.1 Download</a></li>
                    <li><a href="#">3.1.2 Tutorial</a></li>
                </ul>
            </li>
            <li><a href="#">3.2 Mootools</a></li>
            <li><a href="#">3.3 Prototype</a></li>
        </ul>
    </li>
</ul>

Thats it for the HTML part; without CSS styling our menu looks like this: Step 1

Now for the stylesheet part:

#nav, #nav ul{
     margin:0;
     padding:0;
     list-style-type:none;
     list-style-position:outside;
     position:relative;
     line-height:1.5em;
 }

This removes the indents browsers tend to make, as well as the bullets from #nav and all its child-ul elements. The "position:relative" is needed since we will arrange some of the contained elements with position:relative and absolute. This is necessary since relative and absolute positioned elements are positioned according to their containing blocks with a position attribute, other then static.

Line-height defines the height of each list item. You could set the height attribute for your list-items to define their height, but line-height will center the link text vertically without the need to play with margins and paddings.

 #nav a:link, #nav a:active, #nav a:visited{
    display:block;
    padding:0px 5px;
    border:1px solid #333;
    color:#fff;
    text-decoration:none;
    background-color:#333;
 }

#nav a:hover{
    background-color:#fff;
    color:#333;
}

This one is pretty straight forward:
it will style each hyper link in our menu a little bit. At this time the menu looks like this: Step 2

Now lets add some more styles:

#nav li{
    float:left;
    position:relative;
}

This will align our list elements horizontally.

#nav ul {
    position:absolute;
    width:12em;
    top:1.5em;
    display:none;
}

This will position the nested Lists right beyond the main menu and give them a width of 12em. The width attribute is needed so that the list items within display vertically again. The Top attribute should have the same value as the line-height attribute we defined for #nav.

#nav li ul a{
    width:12em;
    float:left;
}

This will set the width of the hyper links to 12 em (which in combination with the width of the UL set above results in a horizontally displayed sub menu, despite of the ongoing float:left)

#nav ul ul{
	top:auto;
	}	

#nav li ul ul {
    left:12em;
    margin:0px 0 0 10px;
    }

#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li:hover ul ul ul ul{
    display:none;
    }
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li li li li:hover ul{
    display:block;
    }

#nav ul ul and #nav li ul ul define where we display the sub menus.

The hover states define which items we want to show when hovering over an item (only the next sub level, not all of them)

After applying these styles we got this menu: Step3

If you are working with a browser other than IE6 you should have a basic dropdown menu now.

Gogo jQuery!

So lets spice up the menu a little bit. First of all here is the whole jQuery Code I used to create the effect:

function mainmenu(){
$(" #nav ul ").css({display: "none"}); // Opera Fix
$(" #nav li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
		},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
		});
}

 $(document).ready(function(){
	mainmenu();
});

Step by step description:

$(" #nav ul ").css({display: "none"}); // Opera Fix

This is a small fix for Opera, which doesn't hide the menus fast enough, if you hover above them and so creates a flickering effect. $(" #nav ul ") is the jQuery way to select all unordered lists in #nav. Usage of this is similar to selecting CSS elements. The .css({display:"none"}) sets the display attribute for all Unordered lists to none.

$(" #nav li").hover(function(){ // here goes mouse over effect
                  },function(){ // here goes mouse out effect
                               });

This is the jQuery function for hovering. Really simple to use: first function lets you define what happens when you hover over a specific item( in our case a list item), second function is used for the mouse out event.

$(this).find('ul:first:hidden').css({visibility: "visible",display: "none"}).show(400);

This function finds the first hidden unordered list within the currently hovered list item and shows it. The function ".show" works only under specific circumstances, this is why we set the display to none. The number between the braces defines the animation speed in milliseconds.

$(this).find('ul:first').css({visibility: "hidden"});

This is the mouse out event: we use visibility instead of display since the show function mentioned above, sets display to "block" at the end of the animation. This way if you would hover just a short moment over the item the item would not display for the ongoing animation and then pop out all of a sudden. Using visibility prevents this flickering.

 $(document).ready(function(){
	mainmenu();
});

This function will call our mainmenu() function as soon as the html document is ready.

We are done now, if you can't get this to work for any reason, here is a working example for download:

Download Includes: HTML File, CSS File, Javscript Files

Have fun creating your own menu ;)

Update :

I have added some small fixes to the script which were suggested by some of my readers, so thanks for adding improvements. ;)

Another thing I wanted to note: I have seen this script in many templates and wordpress themes now, often used in conjunction with one of wordpress automatic list generating features (wp_list_categories, wp_list_pages)
If you use it that way wordpress adds a title attribute to each link, which can create a flickering effect when the browser tooltip for the title appears. If you are using the script this way you should add the following line of jquery at the beggining of the script to remove the titles:

$(" #nav a").removeAttr("title");

(Last updated 18.09.2008)

Responses to “Create a multilevel Dropdown menu with CSS and improve it via jQuery”

Trackbacks

  1. Creando un menu desplegable (drop down) con jquery | Uno de los otros
  2. Menú desplegable en CSS y jQuery — Tablosign
  3. Unobtrusive Multilevel Dropdown menu with CSS and jQuery
  4. Crea un menú descolgable y multi-nivel con CSS y potenciado con jQuery - CSS | pixelco.us blog
  5. Выпадающее многоуровневое меню | АяксЛайн.ру
  6. Great Resources Elsewhere: June 09 to June 16 - CSSnewbie
  7. Scripts Ajax « Blog de mArkO
  8. links for 2008-06-23 | iKeif
  9. Web 2.0 Announcer
  10. Nice CSS Menu extended with jQuery: htt … « Random Trap
  11. Links of Interest - CSS-Tricks
  12. Create a multilevel Dropdown menu with CSS and improve it via jQuery « Sopheak Peas’s Blog
  13. » Absolutely Gorgeous Picasa Photo Slideshows and a great Horizontal CSS menu tutorial Mayur Jobanputra
  14. cmggraphics blog » Blog Archive » Create a multilevel drop-down menu with CSS and jquery
  15. 19 CSS Menu Tutorials to Spice Up Your Web Designs « JKookServ Hosting Blog
  16. 19 CSS Menu Tutorials to Spice Up Your Web Designs | JKookServ Hosting Blog
  17. 300+ Jquery, CSS, MooTools and JS navigation menus | 1stwebdesigner
  18. 300+ Jquery, CSS, MooTools and JS navigation menus | PaulSpoerry.com
  19. Design Feeds - Create a Multilevel Dropdown Menu with CSS and Improve it via jQuery
  20. Design Feeds - Create a Multilevel Dropdown Menu with CSS and Improve it via jQuery
  21. Using JavaScript in your web site | The Funk House
  22. Nicholas Cristo » Blog Archive » 19 CSS Menu Tutorials to Spice Up Your Web Designs
  23. WordPress Multi-Level Drop Down menu using jQuery | SEOAdsenseThemes.com
  24. 19 CSS Menu Tutorials to Spice Up Your Web Designs | Design Vitality
  25. 110+ javascript / Ajax bookmarks for web developers
  26. 300+ Jquery, CSS, MooTools and JS navigation menus | Neurosoftware web dev
  27. jQuery Menu Roundup | Query7
  28. Top 50 plugins gratuitos e tutoriais para jQuery - Blog do yogodoshi
  29. 13 Excellent Tutorials On Creating jQuery Navigation Menu | DeveloperFox
  30. 13 Excellent Tutorials On Creating jQuery Navigation Menu | Pedram Development
  31. How do I display sub menu nav inline? - Graphic Design Forum and Web Design Forum
  32. 50+ jQuery Tutorials und mehr für Einsteiger und Fortgeschrittene
  33. WebAir Blog » Blog Archive » 17 “Must see” Menu in jQuery
  34. 25 jQuery Tutorials for Improved Navigation Menus
  35. [Javascript]Scaricare un menù javascript - MasterDrive.it - Information Technology Developers Community
  36. 40 Exceptional jQuery Interface Techniques and Tutorials | e-szablony.eu
  37. 15 jQuery Menu Dropdown, iPod Drilldown, and Flyout styles » JOSTUDIO
  38. gezinti menüleri i̇çin 25 jquery kılavuzu | Bilinmeyen Gerçekler Antiduzen - Kralblog
  39. Free XHTML/CSS Template #1 | Ronald Nunez - Freelance Web Designer/Developer
  40. Professional Web Design - 19 CSS Menu Tutorials to Spice Up Your Web Designs
  41. idea’s blog - [转]300+Jquery, CSS, MooTools å’Œ JS的导航菜单
  42. Please Review - x10Hosting Forums
  43. 8 Layout Solutions To Improve Your Designs | How-To | Smashing Magazine
  44. Grumpy Git . org » Blog Archive » 8 Layout Solutions To Improve Your Designs
  45. 8种布局解决方案,改善您的设计 | ⊹⊱⋛⋋ISong榮耀ζ組織™⋋⋛⊱⊹
  46. 8 Layout Solutions To Improve Your Designs | forcto.com
  47. ASP.Net MVC Menu Helper | Technical Blog
  48. 八种布局方案改善你的设计(下) | 互联网的那点事...
  49. 译文|8 layout solutions to improve your designs | 小单的青春异次元
  50. 36 Eye-Catching Jquery Navigation Menus | 1stwebdesigner - Love In Design
  51. Free Collection of Eye-Catching Jquery Navigation Menus | guidesigner.net
  52. 36 Eye-Catching Jquery Navigation Menus « Dogfeeds——IT Telescope
  53. 36个引人注目的导航菜单(下) | ⊹⊱⋛⋋ISong榮耀ζ組織™⋋⋛⊱⊹
  54. 25 jQuery Tutorials for Improved Navigation Menus | brainstorming magazine | use the brain to get ideas
  55. 24 CSS (in some cases with jQuery) Navigation and Menu Tutorials : Speckyboy Design Magazine
  56. 28 Free Top Notch CSS Based Navigation Menu Tutorials
  57. 提升设计品质的8个布局方案[SM] | Beleben Design
  58. | Inseven Designs
  59. 35个夺人眼球的jquery菜单下载 | 设计狂
  60. 提升网页设计品质的8种布局方案
  61. CSS Menu Tutorials « Ti Tasik
  62. 30+ Essential Javascript Framework Supported Navigation Techniques | tripwire magazine
  63. 10 Useful code snippets for web developers « My Blog
  64. 75 Amazing CSS Navigations and Jquery Examples | Design Dazzling
  65. 19 mükemmel css menü örneÄŸi — susuzkuyu
  66. SOHU媒体技术产品中心-创意设计组 » (转)提升设计品质的8种布局方案
  67. 19 CSS Menu Tutorials to Spice Up Your Web Designs
  68. 12?jquery???????? | ????&??????
  69. 50 plugins para jQuery
  70. Menu và Tab các ki?u - Mr[K]id – Lê Quang ??c
  71. ???? » 36?????JQuery????
  72. Blog do Villela » Blog Archive » 50 plugins para JQuery!
  73. Gracefully Degradable jquery Drop-Down-Menu – Okada Design Blog
  74. Yoc – A Web Of Flying » 36?????JQuery????
  75. Okada Design Blog » Blog Archive » z-index problem with IE
  76. JS?????? « ????
  77. Web Geli?tiricileri için 10 Kullan??l? Kod Parças? - Dinozorus.com
  78. ???????8????? | ??????
  79. 42 jQuery Navigation based Techniques | Codrops
  80. 30+ Essential Javascript Navigation Techniques « VECTOR Tutorial
  81. Jquery superb navigasyon menüleri | Faydal?Web | Internetin Faydal? Yüzü
  82. ??????? » [Web] ????
  83. 26 jQuery Plugins for Superb Navigation | WebDesignFan.com
  84. 300+ Jquery, CSS, MooTools and JS navigation menus
  85. Create a Multilevel Dropdown Menu with CSS and Improve it via jQuery « Jbloo
  86. 13 Excellent Tutorials On Creating jQuery Navigation Menu | DevWebPro
  87. 40 jQuery Plugins, Tutorials, Resources And Tools Of 2009 | Tweeaks Design
  88. ???? » 36?????JQuery????
  89. jQuery Navigation Menus: A look at 13 Tutorials « Web Design
  90. Nicholas Cristo » Designer Toolbox: 19 CSS Menu Tutorials
  91. Gotowe skrypty jquery, mootools « Sebastian Sobieraj
  92. 13 Excellent Tutorials On Creating jQuery Navigation Menu « Nulls
  93. ??JQuery??WordPress?????? | ????? Zack Live - ?????????????
  94. ??JQuery??WordPress?????? | ????? Zack Live - ?????????????
  95. Multilevel Dropdown « FlagMag
  96. 8??????????? | o??? -- W3C????????
  97. ????
  98. 36?????JQuery???? | TechTrack- ????

Leave a Reply