Simplest menu using CSS

Amr Elgarhy
TreeNodes
Published in
2 min readOct 3, 2011

Many web designers I met had problems while creating menus, specially which contains nested sub menus.

In some cases it is a real pain, but in most of cases it is simple, and the problem come when the designer start to implement the simple menu the hard wrong way, it will take ages from him to implement a simple menu while it just need few lines of css code.

Also he may think it can’t be done without javascript and jquery.

Try to think simple while writing your next menu and may be you will need my code as a starting point for a more complex menu.

What I am listing here is a very simple menu, putting in mind that this menu may contain infinite number of submenus.

Lets start with html:

<ul>
<li>Main 1 >
<ul>
<li>Sub 1 >></li>
<li>Sub 2 >>
<ul>
<li>Sub SUB 1</li>
<li>Sub SUB 2</li>
<li>Sub SUB 3</li>
</ul>
</li>
<li>Sub 3</li>
</ul>
</li>
<li>Main 2 >
<ul>
<li>Sub 1</li>
<li>Sub 2</li>
<li>Sub 3</li>
</ul>
</li>
<li>Main 3 ></li>
<li>Main 4 ></li>
</ul>

This html use UL and LI to draw the menu html, you can use divs instead of UL and LI, this will not cause a problem.

The only hint I can point about the previous html code is that the sub menus html are inside the parent menu html.

Such as ‘Sub 1 >>’ is inside the parent ‘Main 1’, this will make our job easier.

Next CSS:

[sourcecode language=”css”]
ul li ul li
{
clear: both;
}

li
{
list-style-type: none;
float: left;
margin: 0 10px;
cursor: pointer;
width:100px;
}

li ul
{
display: none;
padding: 0;
}

li:hover &gt; ul
{
display: block;
}
[/sourcecode]

The most important lines for us are starting from line 15, everything before this is just for making things looks better and formatted better.

As you see it is just 4 lines of code to make the menu functional, the trick exists in line 21, which will show the UL which exists under any LI and the user hovered on it, and the ‘>’ means that we will show just the first level of UL not all nested UL.

Feel free to add more nested submenus and see how simple it is.

Demo

--

--