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
- The CSS Flexbox Playground
- The sample from the Try it button
Steps
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.
Put them in a row and centre vertically
Keep
flex-directionon row, the default. Setalign-itemsto center so items of different heights line up in the middle of the bar. Setgapto 16 px for even spacing.Push the buttons to the right
Click item 2 and set
flex-growto 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; }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-wrapto wrap so items move to a second line.Copy and rename
Copy the CSS and HTML. In your site, give the elements meaningful class names, such as
.navand.nav-links, instead ofnth-child, and use a<nav>element for the bar.
Try it yourself
Opens the CSS Flexbox Playground with this tutorial's sample loaded.
Common mistakes
- Using margins for spacing
gapspaces 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.