PDA

View Full Version : Center aligning a horizontal nav bar



wojo1086
Mar 25th, 2010, 02:44 AM
I am having the toughest time getting my horizontal navigation bar to center align. I've looked all over the internet for answers but none of them work. I have an image (a .gif) as the navbar background with a z-index of 1. The navbar has a z-index of 2. It sits fine in the image, but it won't center horizontally in my page. Here's the html file with the css file following it:


<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>

<div id="topbar">
<IMG border="0" src="logo.jpg" width="600" height="120">
</div>
<div id="navcontainer">
<ul id="nav">
<li><a href="startsearch.html">Recipe Search</a></li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<li><a href="browsemain.html"> Browse Recipes</a></li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<li><a href="recipesubmit.html"> Submit Your Own Recipe</a></li>
</ul>
</div>
<div id="navbarbackground">
<IMG src="navbar.gif" width=100% height="48">
</div>
</body>
</html>

And the css file:


body {
background:white;}

#topbar {
text-align:center;
background:white;}
#navbarbackground {
z-index:1;
position:relative;}

#navcontainer {
background:pink;
margin-left:auto;
margin-right:auto;}



#nav {
margin:0;
padding:0;
z-index:2;
position:absolute;
padding-top:10px;
white-space:nowrap;}
#nav li {
display:inline;
padding:0;
margin:0;}
a {
text-decoration:none;
color:white;
font-weight:bold;
font-size:22px;
font-family:arial,helvetica,sans-serif;}

Excavator
Mar 25th, 2010, 02:55 AM
Hello wojo1086,
I see you have left/right margin:auto; on #navcontainer and that is one method of centering but you're missing a few key parts.

To center an element you need three things:

a DocType Declaration - see the link in my sig about DocTypes
an element with a width
that elements right/left margins set to auto

For that to work you will probably want to get rid of your absolute positioning.
Even better, there is some divitis (http://ahsanity.wordpress.com/2007/05/15/divitis-and-classitis-two-new-words-in-my-css-vocabulary/) happening there. You could clean that up using more semantic markup (http://robertnyman.com/2007/10/29/explaining-semantic-mark-up/).

There are several centered horizontal menu examples here - http://nopeople.com/design/CSS%20tips/index.html