Create dropdown menus with CSS only

June 20, 2009

I rarely see drop down menus that behave like drop down lists, but I really like them. I noticed, however, that people often use JavaScript to achieve this effect. Actually, there is a simple way to do it only with CSS.

View demo

You are probably familiar with the menu structure; nested unordered lists are common way to create menus.

Showing/hiding child menus is done with simple CSS: ul > li:hover ul. By using this selector we can define behavior of all child menus. When creating normal menus, besides display:block we set some other styles like background color and so on. The only difference between regular menus and “drop down list menus” is in the fact that we don’t set styles for nested UL but rather for LI that is hovered (ul > li:hover).

#header { height:120px; position:relative;
background: transparent url(header_bkg.png) repeat-x scroll top center;}
#nav { margin:0px; padding:0px; position:absolute; top: 70px; display:block;}
#nav > li { list-style-type:none; float:left; display:block; margin:0px 10px; 
position:relative; padding:10px; width:100px;}
#nav > li:hover ul { display:block; }
#nav > li:hover { background-color:#808080; -moz-border-radius:10px; -webkit-border-radius:10px; }
#nav li ul { margin:0px; padding:0px; display:none;}
#nav li ul li { list-style-type:none; margin:10px 0 0 0;}
#nav li ul li a { display:block; padding:5px 10px; color:#A2E200; text-decoration:none;}
#nav li ul li:hover a { background-color:#606060; -moz-border-radius:5px; -webkit-border-radius:5px;}
#nav li span { cursor:pointer; margin:0px 10px; font-weight:bold; }

This is how it can be done jus with CSS. I really can’t figure out why would someone use JavaScript for this, except for adding animations or other effect. Please note that this code doesn’t work in IE6 (this poor browser just doesn’t know what ul > li means).

Thanks for reading. Let's discuss this on twitter.