Centering Horizontal Navigation
When creating horizontal navigation for a layout, it is usually desirable to center it. This tutorial will teach you how.
With this type of navigation, you must place your links in a list. To do this, you should have a code similar to the following:
<ul> <li><a href="url">Link One</a> <li><a href="url">Link Two</a> <li><a href="url">Link Three</a> <li><a href="url">Link Four</a> <li><a href="url">Link Five</a> </ul>
First, you need to create a container in which to center your navigation. To do so, use the following code.
#navcontainer{
width: 100%;
overflow: hidden;
float: left;}
Next, create an ID to house your actual navigation. The margin and padding settings make sure that your navigation doesn’t float away from the side of its container, and the remainder of the following code is necessary to center the navigation. If you would like your navigation to span across a certain width, you can enter that here as well.
#nav{
margin: 0;
padding: 0;
float: left;
position: relative;
left: 50%;}
Now, define an li within the ID you just created above. No styling should be done in this section, unless you want each link to be a certain width, in which case you should divide the total width you have specified in the code above by the number of links you intent to have. List-style: none; takes away those ugly bullet points, and everything else here is again simply needed for the centering.
#nav li{
list-style: none;
position: relative;
float: left;
right: 50%;}
Now it’s time to have some fun and style your links! None of the following code is necessary for centering your navigation; it’s all for styling now.
The only part of this that you need to keep is the display: block;, since that is what makes the links appear in a horizontal line. I have added some basic styling to this:
#nav li a{
display: block;
background-color: #000000;
text-align: center;
color: #ffffff;
font-family: georgia;
font-size: 12pt;
text-decoration: none;
padding: 10px;
font-weight: normal;}
#nav_tut li a:hover{
display: block;
padding: 10px;
font-weight: normal;
background-color: #585857;}
Finally, to implement all of the ID’s described above, your code must look something like this:
<div id="navcontainer"> <ul id="nav"> <li><a href="url">Link One</a> <li><a href="url">Link Two</a> <li><a href="url">Link Three</a> <li><a href="url">Link Four</a> <li><a href="url">Link Five</a> </ul> </div>
Final Result
Here is the coding I described above implemented with some random centered links. Good luck, and please feel free to contact me with any questions or comments regarding this tutorial.
