Search code examples
cssflexboxcentering

Centering flex items inside a list


So I'm having a problem centering items from a menu I'm making.

I have tried to put justify-content: center but that does not seem to work. Can someone help?

Right now the menu is stuck on the left corner. I want to center it.

.header2 {
  background-color: rgb(190, 13, 13);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 15px;
}

.menu {
  display: flex;
}

.menu li {
  margin-right: 15px;
}

.menu li a {
  display: block;
  padding: 10px;
}
<nav class="header2">
  <ul class="menu">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Products</a></li>
    <li><a href="#">Contacts</a></li>
  </ul>
</nav>


Solution

  • The nested flexbox (.menu) is set, by default, to flex-grow: 0, which means it won't occupy the full length of the parent.

    Therefore, applying justify-content: center has no effect because there's no free space available in the container.

    enter image description here

    Adding flex-grow: 1 provides the extra space you need:

    enter image description here

    Add this to your code:

    .menu {
        display: flex;
        flex: 1;
        justify-content: center;
    }
    

    Also, since you're already using the semantically meaningful nav element, there's really no need for a nested list element. Try this simplified code instead:

    .menu {
      display: flex;
      justify-content: center;
      background-color: rgb(190, 13, 13);
    }
    
    .menu a {
      padding: 25px 10px;
    }
    
    .menu a:hover {
      background-color: orangered;
    }
    <nav class="menu">
      <a href="#">Home</a>
      <a href="#">About</a>
      <a href="#">Products</a>
      <a href="#">Contacts</a>
    </nav>