So, now that I work with a team of web developers, I am constantly learning new things. One of the many new things I’ve learned about, is flexbox. I have to admit, I found it very intimidating at first. I figured I’d make a small tutorial about flexbox using a very simple navigation menu.

Flexbox makes things easier, especially when it comes to centering items. One of the main reasons I use Bootstrap in the majority of my projects is due to it being a pain to layout items and get them centered. Using frameworks like Bootstrap and Foundation help you get up and running quickly. However, most developers (I’ve been guilty of this) don’t go back and remove the unused CSS or use a CDN where most users will have the file cached, but for those who don’t, well it could take a bit more time to load.

With a few lines of CSS, we can get a very simple navigation menu centered and listed horizontally. For this example, I’ll just use an unordered list.

<body>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</body>

HTML output

We’ll add a bit of styling to make our page look a bit more presentable.

li {
  list-style: none;
  padding: 15px;
}

li:hover {
  color: red;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 5px;
  cursor: pointer;
}

a {
  text-decoration: none;
  color: inherit;
}

HTML output

Alright, now it’s starting to look like a navigation menu. Now we just need to add display: flex; to the container of the items we want to center. In this case, it’s the <ul> .

HTML output

The default value for flex-direction: row; ,which just so happens to be what we need. Now we need to add justify-content: center; and we’re done.

HTML output

The complete CSS file looks like:

ul {
  display: flex;
  justify-content: center;
}

li {
  list-style: none;
  padding: 15px;
}

li:hover {
  color: red;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 5px;
  cursor: pointer;
}

a {
  text-decoration: none;
  color: inherit;
}

Check out the codepen

Flexbox offers a lot more than just giving us the ability to quickly center elements. I plan on writing a few more posts on the topic, but you should check out two great resources I’ve found. CSS-Tricks has a great post on it called A Complete Guide to Flexbox that I refer to quite frequently and Wes Bos has some awesome free video tutorials to help get you started.