Home > other >  How do I align one navbar item to the right in Bootstrap 5.3 (v5.3.0-alpha1)?
How do I align one navbar item to the right in Bootstrap 5.3 (v5.3.0-alpha1)?

Time:01-03

I tried to align a dropdown link in my Bootstrap 5.3 navbar to the right, but I didn't succeed at all. In Bootstrap 3 it was navbar-right, in Bootstrap 4 I think it was ml-auto, and in Bootstrap 5 beta it was me-auto.

I tried <ul navbar-nav mr-auto> <ul navbar-nav ml-auto> thinking the item would go to the right end of the navbar, but none of them worked.

CodePudding user response:

Try this code:

/* There is no href destination, so you need to use a style to make the cursor a pointer */

.dropdown-toggle {
  cursor:pointer;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Navbar -->
<nav >
   <div >
      <a  href="#">Navbar</a>
      <div >
      <!-- This is essential for the alignment -->
         <ul >
            <li >
               <a  data-bs-toggle="dropdown" aria-expanded="false">
               <strong>Dropdown</strong>
               </a>
               <!-- Make sure to use "dropdown-menu-end", or else the dropdown will overflow -->
               <ul >
                  <li><a  href="#">Action #1</a></li>
                  <li><a  href="#">Action #2</a></li>
                  <li><a  href="#">Action #3</a></li>
                  <li>
                     <hr >
                  </li>
                  <li><a  href="#">Another action</a></li>
               </ul>
            </li>
            <li>
               <a type="button" data-bs-toggle="collapse" data-bs-target="#searchbarcontainer" aria-expanded="false" aria-controls="searchbar"><i ></i></a>
            </li>
         </ul>
      </div>
   </div>
</nav>
<!-- / Navbar -->

What I did there was use the unordered list to make everything inside of it to align to the right. So, if you add anything else to the nav inside of that ul it will be right-aligned.

I recommend adding a breakpoint in your css to remove visibility at 233px so that the navbar doesn’t look funky. However, you may also choose to use the navbar-toggler.

I will always advise to read the documentation on navbars and spacing by the official Bootstrap team.

Hope this helps!

Further readings:

https://getbootstrap.com/docs/5.3/components/navbar/

https://getbootstrap.com/docs/5.3/utilities/spacing/

  • Related