CSS: Creating a horizontal menu/navigation bar

Posted on: Mar 10, 2010 by wenbert

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 ;-)


Subscribe to comments Comment | Trackback |
Post Tags: , ,

Browse Timeline


Comments ( 3 )

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

Dan added these pithy words on Mar 10 10 at 4:48 PM

@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.

Wenbert added these pithy words on Mar 10 10 at 11:11 PM

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

Shopping Cart added these pithy words on Apr 27 10 at 7:34 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!