DEV Community


Posted on

Positioning nav-items in navbar with Flexbox

Hello all :)

This is my first official blog post here as an aspiring front-end dev.

Today's topic is on how to position any number of nav-items in a Bootstrap navbar (within the ul) using Flexbox which is already enabled in Boostrap.

Let's start with the code required for the full navbar first.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        <li class="nav-item">
          <a class="nav-link" href="#">Features</a>
        <li class="nav-item">
          <a class="nav-link" href="#">Pricing</a>
        <li class="nav-item">
          <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>

So the basic navbar I have looks like this

Alt Text

If you need a navbar with more features (a search bar perhaps?) check the Boostrap docs out here.

Centering the nav-items

Alt Text

To center the nav-items as you see above all you have to is enter "justify-content-center" into your code with the id="navbarNav". See below for actual code.

<div class="collapse navbar-collapse justify-content-center" id="navbarNav">

Right-aligning the nav-items

Alt Text

Again all you have to do is "justify-content-center" to "justify-content-end".

And that's it!

BONUS- when the items are in the center you can space them apart by playing with the margin property in bootstrap. See what I did to get the below.

By inserting mr-4 (margin-right-4) into each nav-item class we can make our nav items get more space for each other making our navbar look like

Alt Text

to this

Alt Text

That's it folks! I dream of becoming a great front-end dev soon and hope that this little piece of information can help you as it helped me :)

Top comments (0)