Search code examples
htmlcsscenternav

Navbar will not center, am I missing something?


This is the first site I've attempted to build on my own. Its meant mainly for practice to hone my skills. I have tried several different recommended methods to center this nav manu and nothing is working. Here is my code so far. I feel there is something very obvious that I am missing.

.topnav {
  width: 100%;
  float: left;
  margin: 0 0 1em 0;
  overflow: hidden;
  background-color: antiquewhite;
  border-radius: 15px;
}

.topnav ul {
  padding: 0;
  margin: 0;
  width: 800px;
  list-style: none;
}

.topnav li a {
  float: left;
  margin: auto;
  display: block;
  color: black;
  text-align: center;
  padding: 8px 16px;
  text-decoration: none;
  font-size: 17px;
  border-radius: 15px;
}

.topnav a:hover {
  background-color: white;
  color: black;
}

.topnav a.active {
  background-color: lightgrey;
  color: black;
}
<body>

  <header>
    <h1>The Chromeria</h1>
    <nav class="topnav">
      <ul>
        <li><a class="active" href="Chromeria%20Home.html">The Chromeria</a></li>
        <li><a href="The%20Books.html"> Books </a></li>
        <li><a href="Characters.html"> Characters </a></li>
        <li><a href="Locations.html"> Locations </a></li>
        <li><a href="Luxin.html"> Luxin </a></li>
        <li><a href="Forums.html"> Forums </a></li>
      </ul>
    </nav>
  </header>


Solution

  • There's a lot to be changed. Please look at the CSS code in the snippet below. The most important things: No floats, inline-block vs. inline display, no fixed width for the ul, no auto margins, text-align: center for the container and others:

    .topnav {
      width: 100%;
      margin: 0;
      background-color: antiquewhite;
      border-radius: 15px;
      text-align: center;
    }
    
    .topnav ul {
      padding: 0;
      list-style: none;
    }
    
    .topnav li {
      display: inline-block;
      padding: 8px 0;
    }
    
    .topnav li a {
      display: block;
      padding: 8px 16px;
      color: black;
      text-decoration: none;
      font-size: 17px;
      border-radius: 15px;
    }
    
    .topnav a:hover {
      background-color: white;
      color: black;
    }
    
    .topnav a.active {
      background-color: lightgrey;
      color: black;
    }
        <h1>The Chromeria</h1>
        <nav class="topnav">
          <ul>
            <li><a class="active" href="Chromeria%20Home.html">The Chromeria</a></li>
            <li><a href="The%20Books.html"> Books </a></li>
            <li><a href="Characters.html"> Characters </a></li>
            <li><a href="Locations.html"> Locations </a></li>
            <li><a href="Luxin.html"> Luxin </a></li>
            <li><a href="Forums.html"> Forums </a></li>
          </ul>
        </nav>