Search code examples
htmlcssweb-applicationsnavbarbootstrap-5

How to align Navbar with brand centered in Bootstrap 5


I am trying to center a navbar in Bootstrap 5, but without success. I want both the logo and the links to all be centered, but the navbar is still collapsed via the navbar toggler if the screen is too small. Here is my code:

<nav class="navbar navbar-light navbar-expand-md justify-content-center">
    <div class="container-fluid"><a class="navbar-brand" href="#">Brand</a><button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navcol-1"><span class="visually-hidden">Toggle navigation</span><span class="navbar-toggler-icon"></span></button>
        <div id="navcol-1" class="collapse navbar-collapse">
            <ul class="navbar-nav">
                <li class="nav-item"><a class="nav-link active" href="#">First Item</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Second Item</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Third Item</a></li>
            </ul>
        </div>
    </div>
</nav>

I've been watching tutorials like this one: https://www.youtube.com/watch?v=1quNxUhmZNQ

But I think there is a simpler solution that I just can't come up with at the moment. Any help is appreciated.


Solution

  • Follow what's the video is showing :

    1. add justify-content-center to container-fluid
    2. add flex-grow-0 to navbar-collapse
    3. add text-center to navbar-nav

    After applied to your code and below is the result and I believe this is the simplest method of overwrite the default nav CSS to achieve what you want.

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    
    <nav class="navbar navbar-light navbar-expand-md">
      <div class="container-fluid justify-content-center">
        <a class="navbar-brand" href="#">Brand</a>
        <button class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navcol-1">
          <span class="visually-hidden">Toggle navigation</span><span class="navbar-toggler-icon"></span>
        </button>
        <div id="navcol-1" class="collapse navbar-collapse flex-grow-0">
          <ul class="navbar-nav text-center">
            <li class="nav-item"><a class="nav-link active" href="#">First Item</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Second Item</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Third Item</a></li>
          </ul>
        </div>
      </div>
    </nav>