Horizontal Navigation Bar with Sub Menu

If you have read the previous article on how to create a simple horizontal navigation bar then this is the next step after it. What if you want to add few sub-menus below any of your main menu item? In this article I'm going to show you how to do the same.

Demo

This is how our navbar will finally look. Hover on the language button, it will pop up a few sub menu below it.



Concepts

Check out the code below that I used. What I'm going to do is insert a ul element as a child of li element for which I want to create a sub menu. Here in the code, inside li having 'Language' text I inserted a ul element as its child. Initially to hide the child ul, make its display property as none. On hovering parent li, the child ul should appear below it. To make this happen, assign all li elements a position of relative and child ul a position of absolute. Now the absolute ul elements will appear according to relative positioned li elements. Rest of the code is easy to understand.

Code

Finally here's all the code that you need. Save both files in the same folder. File names have been written above the code.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Creating buttons using CSS</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Navigation Bar - Syntax Page</h1>
<ul class="holder">
<li><a href="#" class="mymenu">Home</a></li>
<li><a href="#" class="mymenu">Language</a>
	<ul>
		<li><a href="#" class="mymenu">C</a></li>
		<li><a href="#" class="mymenu">Java</a></li>
		<li><a href="#" class="mymenu">PHP</a></li>
	</ul>
</li>
<li><a href="#" class="mymenu">Contact Us</a></li>
</ul>
</body>
</html>

style.css

.holder, .holder li
{
	margin:0;
	padding:0;
}
.holder
{
        list-style-type:none;
}
.holder li
{
	position:relative;
	float:left;
}
a.mymenu
{
	background:#ff0000;
        border:2px outset #ff0000;
	color:#fff;
	text-align:center;
	text-decoration:none;
	width:189px;
	padding:10px;
	display:block;
}
a.mymenu:hover
{
	background:#0000ff;
        border:2px inset #0000ff;
}
.holder li ul
{
	display:none;
	position:absolute;
	list-style-type:none;
	padding:0;
	margin:0;
}
.holder li:hover > ul
{
	display:block;
}

There are few things that I want to explain in this code. Check out the last property '.holder li:hover > ul'. Let me explain it in bits. '.holder li' means that all the li elements inside holder class. '.holder li:hover' allow us to decide what to do if someone hovers the li elements within holder class. Lastly > means to select only the first ul present within the li element of holder class.

So altogether, it says that on hovering over li element present inside holder class change display as block for first ul element present inside li element of holder class.