Search code examples
cssflexboxcss-positionnavbarcentering

How to center list items with flexbox?


I am trying to create a navbar with heading on the left, and list items centered. I used flexbox to horizontally line links. Then ı added margin: auto to ul which moved them to left but did'nt centered them symetrically. I am guessing there is no space for the ul to move anymore. I checked other similiar posts but couldn't quite figure what the problem is. Thank you for your time.

HTML

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

body {
    font-family: 'Open Sans', sans-serif;
    background: #fff;
    color: #333;
    line-height: 1.6;
    background: url('/img/showcase.jpg.jpg');
}


#navbar  {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    top: 0;
    width: 100%;
    height: 60px;
    background-color: rgba(10, 10, 10, 0.5);
}

#navbar ul {
    display: flex;
    justify-content: space-around;
    text-align: center;
    margin: 0 auto;
    padding: 0;
}

#navbar li {
    list-style: none;
    padding: 20px;
}
<nav id="navbar">
        <div class="logo">
            <h1>Welcome</h1>
        </div>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Home</a></li>
            <li><a href="#">Home</a></li>
            <li><a href="#">Home</a></li>
        </ul>
    </nav>


Solution

  • If I correctly understood your question (please, let me know), this is what you're after:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      background: #fff;
      background: url('/img/showcase.jpg.jpg');
      color: #333;
      font-family: 'Open Sans', sans-serif;
      line-height: 1.6;
    }
    
    #navbar,
    #navbar ul {
      display: flex;
    }
    
    #navbar {
      align-items: center;
      background-color: rgba(10, 10, 10, 0.5);
      height: 60px;
      justify-content: space-between;
    }
    
    #navbar ul {
      justify-content: center;
      width: 100%;
    }
    
    #navbar li {
      list-style: none;
      margin: 0 10px 0 10px;
    }
    
    .logo {
      margin-left: 20px;
    }
    <nav id="navbar">
      <div class="logo">
        <h1>Welcome</h1>
      </div>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
      </ul>
    </nav>