Align nav-items to right side in bootstrap-4 [duplicate]

TL;DR:

Create another <ul class="navbar-nav ml-auto"> for the navbar items you want on the right.
ml-auto will pull your navbar-nav to the right where mr-auto will pull it to the left.

Tested against Bootstrap v4.5.2

<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
  <style>
    /* Stackoverflow preview fix, please ignore */
    .navbar-nav {
      flex-direction: row;
    }
    
    .nav-link {
      padding-right: .5rem !important;
      padding-left: .5rem !important;
    }
    
    /* Fixes dropdown menus placed on the right side */
    .ml-auto .dropdown-menu {
      left: auto !important;
      right: 0px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary rounded">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="navbar-nav mr-auto">
    <li class="nav-item active">
      <a class="nav-link">Left Link 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link">Left Link 2</a>
    </li>
  </ul>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item">
      <a class="nav-link">Right Link 1</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">            Dropdown on Right</a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action with a lot of text inside of an item</a>
      </div>
    </li>
  </ul>
</nav>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
</body>
</html>

As you can see additional styling rules have been added to account for some oddities in Stackoverflows preview box.
You should be able to safely ignore those rules in your project.

As of v4.0.0 this seems to be the official way to do it.

EDIT: I modified the Post to include a dropdown placed on the right side of the navbar as suggested by @Bruno. It needs its left and right attributes to be inverted. I added an extra snippet of css to the beginning of the example code.
Please note, that the example shows the mobile version when you click the Run code snippet button. To view the desktop version you must click the Expand snippet button.

.ml-auto .dropdown-menu {
    left: auto !important;
    right: 0px;
}

Including this in your stylesheet should do the trick.

Leave a Comment