CSS Navigation Bar

With any website a navigation bar is important, as it allows visitors to navigate your website and it provides a first impression on what the website is about (e.g. if you were offering a product or service you would have products and services in the menu bar).

Simple navigations can be created using CSS while advanced ones require JavaScript. In this tutorial we will create a horizontal and vertical navigation bar.

The first step is to insert our HTML markup; this is typically an unordered list:

HTML Markup

<ul>
       <li><a href="#01">Home</a></li>
       <li><a href="#02">About</a></li>
       <li><a href="#03">Products</a></li>
       <li><a href="#04">Services</a></li>
       <li><a href="#05">Contact</a></li>
</ul>

This is an unordered list with some links, and it is the only HTML markup we need.There are many ways to create a navigation bar in CSS. In this example we will create a simple menu.

CSS

<ul> element

ul {
       list-style-type: none;
       width: 500px;
       margin:0 auto;
}

The first thing you want to do is remove the bullets which are applied to <ul> elements. Next, set the desired width for the menu. Lastly we want the menu to be in the center, so we set the margin left and right to auto. The only compulsory part here is the list-style-type; you don’t need to specify the other options.

<li> element

ul li {
       float: left;
       border-right:1px solid #5E5E5E;
}

Now we are targeting the <li> element in the <ul> element (we are using type selectors). For the <li> element you need to float it to the left; this will make it display horizontally. If you wish you can set a border as well.

ul li:last-child {
       border-right: none;
}

Since the <li> element has a right border, we do not want to apply this to the last <li> element. So we must remove the border:

<a> element

ul li a {
       display: block;
       padding: 25px;
       background-color: #333;
       color: #FFFFFF;
       font-family: "Times New Roman", Times, serif;
       text-decoration: none;
}

Next we target the anchor tag in the <li> element. Here you must set the display:block which forces an element to display as a box block. We must set the spacing, and we do this via the padding. The rest of the properties are to set the styling to make it look appealing.

ul li a:hover {
       background-color: #676767;
}

Lastly set the hover state, so when the user hovers over a menu item, the background colour will change.

This is a simple horizontal menu. If you wish to make it vertical the simply change float property for the <li> tag.

ul li {
       border-bottom: 1px solid #5E5E5E
       width: 200px
}

If we remove the float property it will force each <li> element to display vertically, and then we set the width. If you do not set the width it will be inherited from the parent container, which is the <ul> element. Lastly, make sure you change the border to border-bottom instead of right.

See Demo