Search code examples
csshyperlinknavbarcenter

Can't center the links in navbar with logo on the left


I'm trying to center the links in navbar with logo on the left, but nothing works - how can I do this? Everything either shifts too much to the right or doesn't want to shift at all.

I will be very thankful for any help.

.logo {
  float: left;
  margin-top: -10px;
  height: 30px;
}

.navbar {
  display: flex;
  text-align: left;
  overflow: hidden;
  background-color: black;
  position: fixed;
  top: 0;
  box-shadow: 0px 1px 10px #333;
  width: 100%;
}

.navbar a {
  display: inline-block;
  color: #ffffff;
  text-align: center;
  font-family: Calibri;
  padding: 15px 20px;
  text-decoration: none;
  font-size: 17px;
}

.navbar a:hover {
  color: gold;
}

@media screen and (max-width: 768px) {
  .navbar a {
    float: none;
    display: block;
  }
}
<div class="navbar">
  <a class="logo" href="index.htm"><img src="styles/logo.png"></a>
  <a href="1.htm">Menu 1</a>
  <a href="2.htm">Menu 2</a>
  <a href="3.htm">Menu 3</a>
  <a href="4.htm">Menu 4</a>
  <a href="5.htm">Menu 5</a>
  <a href="6.htm">Menu 6</a>
  <a href="7.htm">Menu 7</a>
  <a href="8.htm">Menu 8</a>
</div>


Solution

  • Instead of text-align: left; you should use:

    align-items: center;
    justify-content: space-around;
    

    as is customary in flex-boxes. Here it is inserted into your code snippet:

    .logo {
      float: left;
      margin-top: -10px;
      height: 30px;
    }
    
    .navbar {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-around;
      overflow: hidden;
      background-color: black;
      position: fixed;
      top: 0;
      box-shadow: 0px 1px 10px #333;
      width: 100%;
    }
    
    .navbar a {
      display: inline-block;
      color: #ffffff;
      text-align: center;
      font-family: Calibri;
      padding: 15px 20px;
      text-decoration: none;
      font-size: 17px;
    }
    
    .navbar a:hover {
      color: gold;
    }
    
    @media screen and (max-width: 768px) {
      .navbar a {
        float: none;
        display: block;
      }
    }
    <div class="navbar">
      <a class="logo" href="index.htm"><img src="styles/logo.png"></a>
      <a href="1.htm">Menu 1</a>
      <a href="2.htm">Menu 2</a>
      <a href="3.htm">Menu 3</a>
      <a href="4.htm">Menu 4</a>
      <a href="5.htm">Menu 5</a>
      <a href="6.htm">Menu 6</a>
      <a href="7.htm">Menu 7</a>
      <a href="8.htm">Menu 8</a>
    </div>