Aug 13, 2021
Per Djurner

Lining up menu items horizontally

Here's the semantic HTML that's typically used to create a menu:

<nav>
  <ul>
    <li><a href="/">Menu Item 1</a></li>
    <li><a href="/">Menu Item 2</a></li>
    <li><a href="/">Menu Item 3</a></li>
  </ul>
</nav>

There are (at least) two ways to get these menu items to line up next to each other on the page (horizontally instead of vertically that is). Either you can use display: inline-block on the li elements, or you can use display: flex on the ul container element.

You'll often see the inline block approach in older code bases and the more modern flexbox approach in more recent code.

One issue with the inline block approach is that you'll have to deal with the spaces that show up between the elements, at least if you're trying to achieve a pixel perfect design. It can be solved by setting font-size: 0 on the container element (i.e. the ul) and then resetting the font size on the individual list elements.

You don't have this problem with the flexbox approach, but you do have to get rid of the browser's default list styling by setting list-style: none on the ul element.

You can check out the code in more detail on the example pages here:

Home