Horizontally Centered Links
There are many ways to create a navigational menu with centered links when there is no set width, however a lot of these need either JavaScript or a CSS hack to make them work. The method used in this tutorial however will not require either of these and will work in all popular browsers.
Step One –The HTML:
The html is quite simple:
<div id="nav">
<ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>
The reason why there needs to be a div is because the container needs different style information to the unordered list for this technique to work. As the trick to this comes with the way the different elements work with and against each other to position the links within this containing div.
Step Two – CSS:
Lets start first with the containing div:
#nav {
width:100%;
position:relative;
overflow:hidden;
}
While you can change the width to a fixed size it is usually best to keep it at 100% as even if the menu is contained within another div it will just take up 100% of its container.
Next the unordered list:
#nav ul {
float:left;
position:relative;
left:50%;
text-align:center;
}
Even though we are aiming to have these links centered it is important to include the float left, as this will shrink the ul to the size of its content, meaning that it will position exactly where we tell it to.
Position relative is also important in this as it will allow us to move the list to the right by 50%. However this means that the unordered list (ul) starts at the 50% point of the #nav container, so the menu is positioned more to the right. To fix this we need to position the list items (li):
#nav ul li {
float:left;
position:relative;
right:50%;
}
Again the float left is used to shrink the list items to the size of their content, which will help with sizing not just the li’s but also the navigations size overall.
The idea behind positioning the li’s 50% to the right is to counter act the positioning of the unordered list and shift the entire menu along to the left, putting the central point of the menu in the center of the #nav div.
Put all together the css will look like this:
#nav {
width:100%;
position:relative;
overflow:hidden;
}
#nav ul {
float:left;
position:relative;
left:50%;
text-align:center;
}
#nav ul li {
float:left;
position:relative;
right:50%;
}
Once this is in place you can then go in and style the links to fit the design of your site, as this tutorial has just given the minimum css required to make this work instead of also styling the links to look pretty.


twitter
forrst
google+
Rss
5
Comments
Will this work in Internet Explorer 7?
yeah it will work in Internet Explorer 7, it even works in IE6
Nice one Pixie
This is the exact technique that I use!
Keep up the good work
I still refer back to this, thanks Helen
I’m glad that you still find it useful
I really need to start adding some new things to here and stop being so lazy :p