A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

CSS: Creating a horizontal menu/navigation bar

I always forget how to do this. Every time I forget, it takes me about 10minutes searching for the right one. So I am posting it here for my reference.

My HTML would look something like this:

<div id="navbar">
    <ul>
        <li class="first"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Projects</a></li>
        <li class="last"><a href="#">Contact</a></li>
    </ul>
</div>

And my CSS would look something like this:

#navbar {
    background-color: #d90000;
}
 
#navbar ul {
    margin: 0; 
    padding: 0;
    float: left;
}
 
#navbar ul li {
    display: inline;
    list-style-type: none;
    padding-right: 20px;
}
 
#navbar ul li a{
    float: left; 
    text-decoration: none;
    color: white;
    padding: 10.5px 11px;
}
 
#navbar ul li a:visited {
    color: white;
}
 
#navbar ul li a:hover, #navbar ul li .current{
    color: #fff;
    background-color:#bf0000;
}
 
#navbar .first  {
    /*You can put stuff here for the first item in the navbar*/
}
 
#navbar .last  {
    /*You can put stuff here for the last item in the navbar*/
}

Comments or suggestions please ;-)

This entry was posted in General and tagged , , . Bookmark the permalink.

3 Responses to CSS: Creating a horizontal menu/navigation bar

  1. Dan says:

    what the reason to use list tag ?
    if you need gorizontal menu you can do in with only anchor tag.
    in this way you don’t need to use floats and a lot of code

  2. Wenbert says:

    @Dan it can be useful in a lot of ways. For example, using an lists would be good if you want to traverse your links with Javascript.

    You can also “control” the way the menu is displayed using CSS. You can switch from a horizontal navigation bar to a vertical navigation bar without changing your HTML code. This is really useful especially when your HTML code is generated by PHP (or something else). All you have to do is edit the CSS.

  3. Your Example will surely help beginners in builing CSS based menus. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>