Show-Hide Submenu using CSS and HTML Only

Aug 28, 2014
It is common for websites to have submenus under menus.

A common behavior for submenus is that it shall only be visible when the main menu is hovered.

Below are simple code snippets of doing this with HTML and CSS only (no Javascript).

First we'll have the HTML structure.

<ul class="menu">
 <li><a href="">Menu</a></li>
 <li><a href="">A very long Menu</a>  
  <ul class="submenu">
   <li><a href="">Menu</a></li>
   <li><a href="">Menu</a></li>
  </ul>
 </li>
 <li><a href="">Menu</a></li>
 <li><a href="">Menu</a></li>
 <li><a href="">Menu</a>
  <ul class="submenu">
   <li><a href="">A long submenu</a></li>
   <li><a href="">Menu</a></li>
  </ul>
 </li>
 <li><a href="">Menu</a></li>
 <li><a href="">Menu</a></li>
</ul>

We'll include some default styling.


*{padding:0;margin:0;}
body{font:16px Tahoma;padding:10px;}
a{text-decoration:none;}
ul{list-style-type:none;}

So far, our menu would look like this:


Let's add style to our main menu.

.menu{
 position:relative;
}
.menu li{
 float:left;
}
.menu>li>a{
 background:red;
 padding:15px;
 display:block;
 border:1px solid black;
}
.menu>li>a:hover{
 background:orange;
}

We can now distinguish the main and the submenu.
Please do not mind the arrow left on the lower right. That's from a plugin on my browser.
Let us now style the submenu.

.submenu li{
 clear:left;
}
.submenu>li>a{
 background:yellow;
 padding:10px;
 display:block;
 border:1px solid black;
}


Notice that the fifth menu's width is increased because of its submenu. Let's make our submenu absolute so it will not affect the main menu.

.submenu{
 position:absolute;
}



We've already fixed the width for the main menu.
But the submenu seems a little awkward.
This is when we give a fixed width for the submenu so that everything will have the same width.

Add width:120px to .submenu>li>a.


Looking nice so far.
But we need to hide the submenu.
So let's add display:none; to our .submenu class.

Our submenu is now hidden from view.
But this should appear when we hover on its main menu.
So we add the following rule:

.menu>li:hover>.submenu{
 display:block;
}

Tadaan!



Sample Result

We have created a menu with submenu using only HTML and CSS.

Any better ideas? Please leave a message on the comments section.

No comments:

Post a Comment