Arthur de Jong

Open Source / Free Software developer

Simple dropdown menu using only CSS

2005-07-09

These are more or less my notes of an effort to implement a very simple dropdown-like menu that is implemented purely in HMTL and CSS.

It is currently not tested for cross-browser compatibility (it appears not to work in MS IE 5.0) but it should work in most Mozilla-based browsers. If you have any improvements, please send me an email.

This is just a small demo of an idea I had for using CSS in a menu, it is not really production-quality just proof-of-concept.

First try

This solution basically trims the list items to the height of one line if the mouse is not over the list item. This causes the menu to expand one level if the mouse is over an item.

The CSS

ul.menu li {
  display: block;
  width: auto;
  height: 1em;
  overflow: hidden;
}

ul.menu li:hover {
  height: auto;
  overflow: visible;
}

The HTML

<ul class="menu">
  <li>
    Item1
    <ul>
      <li>Item1.1</li>
      <li>
        Item1.2
        <ul>
          <li>Item1.2.1</li>
          <li>Item1.2.2</li>
          <li>Item1.2.3</li>
        </ul>
      </li>
      <li>
        Item1.3
        <ul>
          <li>Item1.3.1</li>
          <li>Item1.3.2</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Item2</li>
</ul>

The result

Open issues and notes

  • if you move from the Item1.2 to the Item1.3 option the 1.2 submenu collapses moving the 1.3 option and collapsing the whole menu (probably)
  • there is a margin or padding problem somewhere making the normal height not 1em
  • the whole menu should be a lot prettier

Second try

This tries to make an effort of only showing the menu if an option is clicked. This solution only shows the lists if they have a pointer over them or have their parent activated. The HTML code is the same as in the previous example.

The CSS

ul.menu ul {
  display: none;
  position: relative;
  bottom: 1em;
  padding-top: 1em;
}

ul.menu li:active ul {
  display: block;
}

ul.menu ul:hover {
  display: block;
}

The result

Open issues and notes

  • if the new sublist shows up it does not automatically have the hover property, you have to move the mouse first (causing an ugly selection)
  • activating an item completely opens the menu, not just one level (using the > CSS child selector did not work for some reason)
  • the whole menu should be a lot prettier