This tutorial will take you through building another real-world component with Flexbox. This time, we will recreate the navigation bar that is found on freeCodeCamp.
The markup is simple enough; there’s an
img tag for the logo and an unordered list containing the navigation links. On the freeCodeCamp website, the navigation bar is built using floats. But we can also use Flexbox to achieve the exact same result with minimal effort as you’ll see in the paragraphs below.
Let’s start by telling the browser that we want to lay out the elements in the navigation bar with Flexbox by setting the
display property of the container element to
.navbar a flex container while its direct children (
.nav-links) become flex items. The navigation links are now removed from under the logo and placed level with it toward the
main-start of the flex container. All the available space is pushed toward the
main-end due to the default value of
We need the available space between the logo and navigation links though, so we’re going to set the value of
space-between to achieve that.
That’s more like it. The first and last flex items have been packed flush against the
main-end respectively, while the available space is now placed between them.
The navigation links don’t look right though. They are stacked on top of each other instead of lining up horizontally. This is due to the default styling of list items in the browser.
Let’s change that up by making
.nav-links also a flex container so that all the list items within it can be laid out according to the Flexbox model.
The list items are now placed next to each other along the
.nav-links. The reason why there’s some space between each link is due to the padding declared under the
.nav-item a selector.
One problem remains though. The logo and navigation links are not aligned properly along the cross axis of the navigation bar. We can fix this by setting
Now the navigation bar looks identical to the one found on the freeCodeCamp website. It was easy wasn’t it?
There’s more to the Flexbox layout model than the handful of properties we’ve covered so far. In the next tutorial, I’ll show you how to build a different component with some new Flexbox properties. Stay tuned!