Bootstrap 5 Update (2021)
The Navbar in Bootstrap still utilizes flexbox for alignment, maintaining the same functionality as in Bootstrap 4.
Bootstrap 4.1+ Update
In Bootstrap 4, the navbar has transitioned to using flexbox for easier alignment. The Website Name
can now be centered by applying mx-auto
. No longer is it necessary to use floats for the left and right side menus.
<nav class="navbar navbar-expand-md navbar-fixed-top navbar-dark bg-dark main-nav">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>
<ul class="nav navbar-nav mx-auto">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Rates</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Demo of Centering Navbar with mx-auto
If there's only one navbar-nav
within the Navbar, you can utilize justify-content-center
for centering as well.
UPDATE
In the previous solution, the Website Name
is centered in relation to the adjacent left and right navbar-nav
, which may cause misalignment if their widths differ.
https://i.sstatic.net/FBwa6.png
To address this issue, one workaround for achieving absolute centering in flexbox can include...
Option 1 - Use position:absolute;
It's acceptable to employ absolute positioning alongside flexbox to center the desired item.
.abs-center-x {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Demo of Centering Navbar with absolute position
Option 2 - Utilize flexbox nesting
Alternatively, you can make the centered item a d-flex
element for center justification. Each navbar component would then need flex-grow:1
.
Beginning with Bootstrap 4 Beta, the Navbar now adopts display:flex
. In Bootstrap 4.1.0, a new class called flex-fill
is introduced to ensure each nav section fills the width:
<nav class="navbar navbar-expand-sm navbar-dark bg-dark main-nav">
<div class="container justify-content-center">
<ul class="nav navbar-nav flex-fill w-100 flex-nowrap">
...
Demo of Centering Navbar with flexbox nesting
Prior to Bootstrap 4.1.0, you could add the flex-fill
class like so...
.flex-fill {
flex:1
}
Starting from version 4.1, flex-fill
is integrated into Bootstrap.
Explore More Navbar Centering Demos in Bootstrap 4
Additional Centering Demonstrations
Center Links on Desktop, Left Align on Mobile
Related:
How to Center Nav Items in Bootstrap?
Bootstrap NavBar with Left, Center or Right Aligned Items
Moving 'Nav' Element Under 'Navbar-Brand' in Navbar
https://i.sstatic.net/MB9wA.png