Search code examples
htmlcsscentering

How to center a navigation bar properly?


I understand, lots of people have asked this question on how to center a navigation bar but when I apply this CSS, it centers it but it aligns the nav bar a bit to the right:

nav {
  text-align: center;
}

nav li {
  display: inline-block;
}

Could this be due to some list items having different lengths or do you think this is a different problem?


Solution

  • Your <ul> most likely has a padding-left, as this is the default. Just check for it in the developer tools.

    nav {
      background: #999;
      text-align: center;
    }
    nav li {
      background: #ccc;
      display: inline-block;
    }
    <nav>
      <ul>
        <li>Menu 1</li>
        <li>Menu 2</li>
        <li>Menu 3</li>
      </ul>
    </nav>

    40px of padding on the left is the default.

    Just apply padding-left:0; on the appropriate <ul> to fix this.