如何在 Tailwind CSS 中水平居中导航栏内容

时间:2021-07-13 18:41:57

标签: html css tailwind-css

我最近开始尝试使用 Tailwind,我决定第一个组件是具有以下特性的基本导航栏。

  • 应位于水平居中屏幕的徽标
  • 徽标两侧的导航链接

这是我尝试的简化版本:

    <nav class=" flex fixed w-screen justify-center items-center text-center">
      <!-- Left Navigation -->
      <div>
        <a class="mx-2">LINK ONE</a>
        <a class="mx-2">LINK TWO</a>
      </div>
      <!-- Logo -->
      <div class="mx-12">L</div>
      <!-- Right Navigation -->
      <div>
        <a class="mx-2">LINK THREEE</a>
        <a class="mx-2">LINK FOOOUR</a>
      </div>
    </nav>

我最初的方法是有一个 flexbox 容器 (nav) 可以容纳三个 div,导航栏的每个部分一个,然后使用 justify-center 类 (justify-content: center;) 直接定位徽标位于屏幕中央,左右导航链接位于两侧。

在我尝试之后,我很快发现 justify-center 类帮助我将所有 div 及其内容沿着容器的轴定位到屏幕的中心。但是,我没有考虑到徽标右侧的文本较长,因此相对于屏幕中心将徽标稍微偏向左侧。

所以,我的问题是,如何将徽标水平居中 - 死心 - 在屏幕上并且不让左侧或右侧导航链接将徽标推离中心?

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式实现:

<nav class="flex fixed w-screen">
    <!-- Left Navigation -->
    <div class="flex-1 flex justify-center mr-auto">
        <a class="mx-2">LINK ONE</a>
        <a class="mx-2">LINK TWO</a>
    </div>
    <!-- Logo -->
    <div class="mx-12">L</div>
    <!-- Right Navigation -->
    <div class="flex-1 flex justify-center ml-auto">
        <a class="mx-2">LINK THREEE</a>
        <a class="mx-2">LINK FOOOUR</a>
    </div>
</nav>

赋予每个弹性项目 flex-1 允许每个项目增长(或缩小)而忽略其初始大小。这会在项目之间平均分配空间。使每个项目成为中心对齐项目并分别使用 mr-automl-auto 平均分配可用空间。