How to Center Navbar Items in Bootstrap Easily
To center navbar items in Bootstrap, wrap the
nav links inside a div with the class d-flex justify-content-center w-100. This uses Bootstrap's flexbox utilities to horizontally center the items within the navbar.Syntax
Use a div with Bootstrap flexbox classes inside the navbar to center items:
d-flex: makes the container a flexbox.justify-content-center: centers items horizontally.w-100: makes the container full width to center items properly.
html
<nav class="navbar"> <div class="d-flex justify-content-center w-100"> <!-- Navbar items here --> </div> </nav>
Example
This example shows a Bootstrap navbar with three centered links using flexbox utilities.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Centered Navbar Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <nav class="navbar bg-light"> <div class="d-flex justify-content-center w-100"> <a class="nav-link" href="#">Home</a> <a class="nav-link" href="#">About</a> <a class="nav-link" href="#">Contact</a> </div> </nav> </body> </html>
Output
A light gray horizontal navbar with three links (Home, About, Contact) centered horizontally in the browser window.
Common Pitfalls
Common mistakes when centering navbar items include:
- Not using
w-100on the flex container, which prevents proper centering because the container shrinks to content width. - Placing
justify-content-centeron thenavbaritself instead of a flex container wrapping the links. - Using
mx-autoon individual links, which centers each link separately instead of the group.
html
<!-- Wrong: Missing w-100, items not centered --> <nav class="navbar bg-light"> <div class="d-flex justify-content-center"> <a class="nav-link" href="#">Home</a> <a class="nav-link" href="#">About</a> <a class="nav-link" href="#">Contact</a> </div> </nav> <!-- Right: Added w-100 for full width --> <nav class="navbar bg-light"> <div class="d-flex justify-content-center w-100"> <a class="nav-link" href="#">Home</a> <a class="nav-link" href="#">About</a> <a class="nav-link" href="#">Contact</a> </div> </nav>
Quick Reference
| Class | Purpose |
|---|---|
| d-flex | Makes container a flexbox for flexible layout |
| justify-content-center | Centers flex items horizontally |
| w-100 | Makes container full width for proper centering |
| nav-link | Styles links inside navbar |
Key Takeaways
Wrap navbar items in a div with classes d-flex justify-content-center w-100 to center them.
Always include w-100 on the flex container to allow full width centering.
Do not apply centering classes directly on individual links or the navbar element.
Use Bootstrap's flexbox utilities for clean and responsive alignment.
Test your navbar on different screen sizes to ensure proper centering.