Search code examples
htmlcsscenter

How can I center a left floating Nav Bar?


I've got this nav bar almost right where I want it, but I just need to center it on the page. How can I center the navigation without changing anything else? No matter what I try, it will always align to the left of the page. I know it's probably because of the "float: left" properties, but changing those ruins the whole navbar layout.

.navbar {
  overflow: hidden;
  background-color: none;
  text-align: center;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: grey;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition-duration: 0.3s;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: grey;
  padding: 0px 0px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.dropdown:hover .dropbtn {
  color: #FFF;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: none;
  margin-top: 45px;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: grey;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: none;
  padding: 12px 25px;
  color: #FFF;
}

.dropdown:hover .dropdown-content {
  display: block;
}

.navbar .focus {
  color: #FFF;
}
<div class="navbar">
  <a href="#home" class="focus">HOME</a>
  <div class="dropdown"><a href="#">PRACTITIONERS
    <button class="dropbtn">
      <i class="fa fa-caret-down"></i> 
    </button></a>
    <div class="dropdown-content">
      <a href="#">Biochemistry</a>
      <a href="#">Biophysics</a>
      <a href="#">Nutrition</a>
    </div>
  </div>
  <a href="#news">CONSUMERS</a>
  <a href="#news">NETWORK</a>
</div>


Solution

  • you can add display flex and justify content center like this

    .navbar {
      display: flex;
      justify-content: center;
      overflow: hidden;
      background-color: none;
      text-align: center;
    }