CSS Flexbox Playground · Tutorial

How to build a navigation bar layout with flexbox

6 min readbeginnerUpdated

Almost every website has a top bar with a logo on the left, links in the middle and a button on the right. This tutorial builds that layout in the Flexbox Playground with four boxes, explains each property, and copies the CSS.

What you need

Steps

  1. Picture the bar as boxes

    Item 1 is the logo, item 2 the group of links, item 3 a search button and item 4 a sign-in button. Set Items to 4. The container is the bar itself.

  2. Put them in a row and centre vertically

    Keep flex-direction on row, the default. Set align-items to center so items of different heights line up in the middle of the bar. Set gap to 16 px for even spacing.

  3. Push the buttons to the right

    Click item 2 and set flex-grow to 1. It takes all the spare space in the row, which pushes items 3 and 4 to the right edge. This is the key trick for navigation bars.

    .container {
      display: flex;
      align-items: center;
      gap: 16px;
    }
    
    .item:nth-child(2) {
      flex: 1 1 auto;
    }
  4. Check narrow screens

    Drag the preview’s corner to make it narrow. The links item shrinks first. On phones you would usually hide the links behind a menu button, or set flex-wrap to wrap so items move to a second line.

  5. Copy and rename

    Copy the CSS and HTML. In your site, give the elements meaningful class names, such as .nav and .nav-links, instead of nth-child, and use a <nav> element for the bar.

Try it yourself

Opens the CSS Flexbox Playground with this tutorial's sample loaded.

Try it now

Common mistakes

Using margins for spacing
gap spaces items evenly and doesn’t add space at the ends. It replaces most margin hacks.
Forgetting align-items
Without align-items: center, a tall logo makes the links sit at the top of the bar.
Putting flex-grow on the wrong item
The item that grows absorbs the space. Put it on the item just before where the gap should be.

Next steps

Go back to the CSS Flexbox Playground, or keep going with one of these:

FAQ

Can I use margin-left auto instead of flex-grow?

Yes. margin-left: auto on item 3 also pushes the last two items right, without stretching the links item.

How do I centre the links exactly?

Give the logo and the button group the same flex-basis so the links sit between equal-sized neighbours, or use CSS Grid with three columns.