Search code examples
htmlcssmarginnav

HTML:Margin auto not working with nav bar


So here's my code:

.nav-item {
  display: inline;
  color: white;
  padding: 30px 10px;
  font-style: bold;
  font-family: sans-serif;
  font-size: 20px;
  width: 1000px;
  margin: 0 auto;
}

.nav-container {
  background-color: black;
}
<nav class="nav-container">
  <span class="nav-item">ABOUT ME</span>
  <span class="nav-item">CONTACT ME</span>
  <span class="nav-item">PORTFOLIO</span>
</nav>

I want to make my navigation bar centered in the middle of the page, with margin: auto, but for some reason, it doesn't work. When I set display: block, it works, but doesn't display in a line. Could someone tell me why this is? Thanks a ton...


Solution

  • Inline elements behave just like text, so you need to put the alignment on the parent.

    In your CSS, remove the margin:0 auto; and add text-align: center; on .nav-container:

    .nav-item{
      display:inline;
      color:white;
      padding:30px 10px;
      font-style:bold;
      font-family:sans-serif;
      font-size:20px;
      width:1000px;
    }
    
    .nav-container {
      text-align: center;
    }
    

    http://jsfiddle.net/5v7Lppkf/