Bootstrap 5 水平居中导航栏

Boostrap 5 Horizontally center navbar

在 Bootstrap 5 文档中,它说使用“​​justify-content-center”class 水平对齐导航元素。

<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
</ul>

参考:https://getbootstrap.com/docs/5.0/components/navs-tabs/#horizontal-alignment

如何水平对齐导航栏?将“justify-content-center”添加到 navbar-nav 不起作用。有没有一种优雅的方法可以使用 BootStrap 的内部 classes 而不是编写自定义 CSS?

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav justify-content-center">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</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">
          <a class="nav-link disabled">Disabled</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

试试这个:

在折叠 div 中添加 justify-content-center class,如下所示

<div class="collapse navbar-collapse justify-content-center" id="navbarNav">

更新:justify-content-center 将在 <ul> 中将内容居中对齐,但是 <ul>collapse navbar-collapse 中,因此您需要将 <ul> 居中div.