19 July 2011

Most simple/basic single level CSS dropdown menu without Javascript tutorial

Sometimes when web demos focus on extended functionality, it's difficult to identify and extract exactly what you need for your own project from the examples. With beginners & newcomers to CSS in mind, I've put together this extremely simple dropdown menu & tutorial. You can take this skeleton and add styling and content for your own project. This menu auto sizes/auto expands to fit its content and could easily be adapted to add more levels, animation or fancy styling.

Check out the demo here

Step by Step:
1. Firstly you'll need to create some links. Here's some I made earlier. Copy the code below somewhere inside your body tags.
Please see the right hand pane before copying my code - Thank you! >>>

<ul id='menu'>
   <li><a href='#'>Colours</a>
     <ul>
         <li><a href='#'>Red</a></li>
         <li><a href='#'>Yellow</a></li>
         <li><a href='#'>Blue</a></li>
     </ul>
   </li>
   <li><a href='#'>Fruits</a>
     <ul>
         <li><a href='#'>Orange</a></li>
         <li><a href='#'>Apple</a></li>
         <li><a href='#'>Bananna</a></li>
     </ul>
   </li>
   <li><a href='#'>No Submenu</a></li>
</ul>
2. Next, you'll need to add styling. Copy the code below and paste inside your style tags or in your external stylesheet.

/*DROPDOWN FUNCTIONALITY*/
/*set up ul tags*/ 
#menu, #menu ul{ padding:0; margin:0}
/*set up a tags*/ 
#menu a{display:block;}
/*position level 1 links horizontally*/ 
#menu li{display:block; float:left;}
/*undo previous style for level 2 links*/
#menu li ul li{float:none;}
/*position level 2 links vertically and hide*/ 
#menu li ul{display:none; position:absolute; z-index:1}
/*unhide level 2 links on li:hover from level 1*/ 
#menu li:hover ul{display:block;}

/*DROPDOWN STYLING:*/
#menu{height:25px}
#menu a{color:#09F; padding:5px 10px 5px 10px;}
#menu a:hover{color:#0CF;}
#menu li{background-color:#FFF; border:solid 1px #CCC;  margin-left:-1px}
#menu li:hover{background-color:#F0F0F0}
3. Test it. Isn't that nice? Now change the links from step 1 and the /*DROPDOWN STYLING*/ section from step 2 until your menu looks as you'd like.

Tested in IE9, Chrome & Firefox but should work across all modern browsers.

12 comments:

  1. Great, but does'nt work. Not in MSIE9 anyway. FF was ok.

    ReplyDelete
  2. ahh, works in MSIE9 if we use your xml doctype tag.

    ReplyDelete
  3. Excellent, many thanks, it really helped me get my head around it.

    ReplyDelete
  4. OK does it work it html im planing some mischief against my teacher because he said he would not teach is il maake one myself

    ReplyDelete