Create a Variable Item Navigation Menu With Flexbox

This is a handy one for making a navigation menu with equal nav item widths regardless of how many items you have. The old methods would be converting the navigation to display: table and making each nav item a cell, using calc(100% / items), or hell even floating the items and manually changing the padding on the nav items.

A demo for this tutorial can be viewed here.

Navigation markup

<nav id="primary-nav">
   <ul>
      <li><a href="#">One</a></li>
      <li><a href="#">Two</a></li>
      <li><a href="#">Three</a></li>
      <li><a href="#">Four</a></li>
      <li><a href="#">Five</a></li>
   </ul>
</nav>

Style our menu and add in our flexbox goodness

We are just styling a standard menu here, which we have previously on Frontend Hero but with a few key flex properties which I have commented.

nav.primary-nav {
   width: 100%;
   float: left;
   background: #de456b;
   margin-bottom: 75px;
}
   nav.primary-nav ul {
      display: flex; /* Gives the UL menu a flexbox layout. */
      flex-direction: row; /* Set list items to be in a row layout */
   }
      nav.primary-nav li {
         display: block;
         flex-grow: 1; /* Make every item equal size */
    	 text-align: center;
         background: #de456b;
         margin: 0;
         border-right: 1px solid #fff;
      }
         nav.primary-nav a  {
            color: #fff;
            padding: 20px;
            display: block;
         }

With those three lines, the menu will always display the nav items equally – Very neat.

You can reply to this post by tweeting to me