Navigation menus using CSS flexbox

The markup for all examples illustrated below are identical as follow:

<nav>
  <ul>
    <li><a href="#" title="Home">Home</a></li>
    <li><a href="#" title="Blog">Blog</a></li>
    <li><a href="#" title="Work">Work</a></li>
    <li><a href="#" title="Resources">Resources</a></li>
    <li><a href="#" title="Meta">Meta</a></li>
  </ul>
</nav>

The CSS code provided in each of the demo below can be toggled. They are written in the flavour of Sassy CSS.

Scenario 1

Equal width elements

This is the equivalent of specifing each element to be an equal fraction of its parent’s full width, i.e. each fraction is of identical size and the sum of their widths is equivalent to the parent’s full width.

This effect is achieved with the help of flex: 1 1 100% on the flex items, which is a shorthand for:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 100%;

The property tells the browser to grow the items equally until they fill the full width of their flex parent, which is the <ul> element in this case. The flex-basis of 100% ensures that all items will be the same size and treated equally.

Of course, this effect can be easily replicated with the good old CSS float and percentage width trick, but this will require knowing the number of children before hand, or else one will have to calculate the percentage width with JS instead.

Show CSS
nav {
  & ul {
    display: flex;
    width: 100%;
    & li {
      flex: 1 1 100%;
    }
  }
}

Scenario 2

Proportionate, content-based width

In other words, the width of each element will be proportionate to its relative width compared to the parent. This ensures a more balanced layout in the sense that wider menu items get more spacing

Here, we use the property flex: 1 1 auto on the children element. It is the shorthand of:

flex-grow: 1;
flex-shrink: 1;
flex-basis: auto;

Like the previous example, flex-grow: 1 allows the children to grow when necessary, but on the condition that the width of each element is based on the size of its content. The latter is achieved with the help of flex-basis: auto.

Show CSS
nav {
  & ul {
    display: flex;
    width: 100%;
    & li {
      flex-grow: 1;
    }
  }
}

Scenario 3

Equally spaced elements + natural width + centered within parent

This is one of the more complicated examples that require a lot of CSS-hacking — without the flexbox specification, one has to set each item to an inline element and then justify them.

The trick here is to declare the wrapping container, <nav>, as well as the list itself, as flex displays — but we only apply the justify-content: center; property to the wrapping container.

Show CSS
nav {
  display: flex;
  justify-content: center;
  & ul {
    display: flex;
    & a {
      padding: 1rem 2rem;
    }
  }
} 

Fancy example 1

Mixing flexbox with CSS transforms

Fancy example 2

Mixing flexbox with CSS transforms