Search code examples
htmlcsscenteringnav

How to center a horizontal navigation bar


I am having trouble centering my navigation bar.

This is the example nav bar I am working with

<style>
/* Begin Navigation Bar Styling */
#nav {
  width: 100%;
  float: left;
  margin: 0 0 3em 0;
  padding: 0;
  list-style: none;
  background-color: #f2f2f2;
  border-bottom: 1px solid #ccc; 
  border-top: 1px solid #ccc; }
#nav li {
  float: left; }
#nav li a {
  display: block;
  padding: 8px 15px;
  text-decoration: none;
  font-weight: bold;
  color: #069;
  border-right: 1px solid #ccc; }
#nav li a:hover {
  color: #c00;
  background-color: #fff; }
/* End navigation bar styling. */
</style>

but as seen, the navigation bar is not centered.

I have tried using auto margins but it doesn't work. How do I go about fixing this?


Solution

  • Add text-align:center; to #nav

    Remove float:left; and add display: inline-block; to #nav li

    Change to this:

    #nav {
        width: 100%;
        float: left;
        margin: 0 0 3em 0;
        padding: 0;
        list-style: none;
        text-align:center;
        background-color: #f2f2f2;
        border-bottom: 1px solid #ccc;
        border-top: 1px solid #ccc;
    }
    #nav li {
        display: inline-block;
    }
    

    JSFiddle Demo