Search code examples
htmlcsstwitter-bootstrapbootstrap-4html-lists

How to shift a single menu item in bootstrap 4 to the right


I am using Bootstrap 4 as part of a Laravel 8 blog system I am doing now. The menu items are well in place but I want to shift the last menu item to the right. I have tried many options including ml-auto but it does not have any effect on the item. I also tried to benefit from previous similar posts but they all proved not to work for my case. I would so much appreciate any assistance in this regard. Please find my code below:

  <nav class="navbar navbar-expand-lg navbar-light navbar-dark bg-dark">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">{{config('app.name', 'Learning')}}</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="nav navbar-nav">

          <a class="nav-link" href="/">Home</a>
          <a class="nav-link" href="/about">About Us</a>
          <a class="nav-link" href="/services">Services</a>
          <a class="nav-link" href="/posts">Blog</a>
          <a class="nav-link" href="/posts/create">Create Post</a>

        </div>
      </div>
    </div>
  </nav>

Solution

  • The first issue is that you say you are using Bootstrap 4, but your syntax is of Bootstrap 5. data-bs-* attributes are for B5, B4 has only data-* attributes.

    Then for aligning the last item to the right, first you'll need your navbar-nav to take all width, thus add w-100 to it. Then you'll need the last item to fill all the remaining space, which you can do by adding flex-fill. And then all you need to do is add the text-end to this same element. Your code becomes:

    <div class="nav navbar-nav w-100">
        <a class="nav-link" href="/">Home</a>
        <a class="nav-link" href="/about">About Us</a>
        <a class="nav-link" href="/services">Services</a>
        <a class="nav-link" href="/posts">Blog</a>
        <a class="nav-link flex-fill text-end" href="/posts/create">Create Post</a>
    </div>
    

    JSFiddle

    Again, if you are indeed not using B5, but B4, then change all the data-bs-* attributes to only data-*, and also text-end becomes text-right.