April 17, 2013

Create a Minimal Cross Browser Dropdown Menu

Demo

I build a menu at least once a week and they range from simple to mega. Some are purely CSS based, while others are heavily dependent on jQuery. This menu is a compromise of both worlds and works in every browser. The menu allows multi-line child links in the dropdown, which helps me because my current user base doesn’t always understand that short is sweet.

Let’s take a look at the HTML code below. It is your standard nested unordered list setup of X-MEN characters. Nothing too fancy.

Now, lets take a look at the CSS. There are some cool things going on to make it work in legacy browsers. First, we give the parent unordered list a zoom property. This tells IE7 and older to give the object a property of hasLayout and allows us to fix some relationships between elements.

There are two redundant hover properties set to the parent unordered list item, that we later set again with jQuery because IE7 and older ignores it.

If you look at the child list item anchor tag, you will see it is set to display as a table-cell and the vertical align is set to middle. With the parent list item set to display as a table, this vertically centers any content. Therefore, if the user adds a longer than expected link title, it will wrap and still center. It does show up a little off in IE6, but degrades pretty gracefully.

The jQuery needed to make this puppy work is pretty minimal. I almost always put jQuery into noConflict mode, which is what is done on the first line.

When the document is ready, it loads our hover function that makes the dropdown show and appends a class of hover. Why do we add the hover class? If you look at the CSS, you will notice that we use it to backup the hover selector in older browsers to keep the main button in a hover state while the user is perusing the dropdown.

Also notice, that there is a ‘this’ declaration when we make the dropdown visible and hidden. If this is left out, the dropdowns will always appear at the far left of the menu rather than below the item that you are hovering over.

Feel free to change things and experiment. It can be easily converted to HTML5, which is how I use it on most sites. And remember, Wolverine is the best member of the X-Men!