Centering the navbar content in Bootstrap 4 (alpha

2019-01-12 11:03发布

问题:

I am trying to center the navbar content in Bootstrap 4, alpha 5. I have been googling a bit, and I guess there might be some trick involving d-block and mx-auto.

However I cannot find out how to center the navigation links so that they are total in center, not just adding a container around them.

Sample navbar code I am playing with:.

<nav class="navbar navbar-light bg-faded">
  <ul class="nav navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown link
      </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <a class="dropdown-item" href="#">Something else here</a>
      </div>
    </li>
  </ul>
</nav>

JSFiddle if you like

回答1:

You could add this code to your css file.

.nav {
  text-align: center;
}

.navbar-nav .nav-item {
  float: inherit;
  display: inline-block;
}


回答2:

Centering Navbar items is simpler in Bootstrap 4, and doesn't require additional markup.

<nav class="navbar navbar-expand-md navbar-light bg-faded">
  <ul class="navbar-nav mx-auto">
    <li class="nav-item active text-center">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item text-center">
      <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item text-center">
      <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item dropdown text-center">
      <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown link
      </a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <a class="dropdown-item" href="#">Something else here</a>
      </div>
    </li>
  </ul>
</nav>

Bootstrap 4 Center Navbar Demo (updated for v4.0.0)

If you need to center only specific elements, such as the Brand or Links, see this answer