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

How to horizontally center navbar content in 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 class (justify-content: center; ) 将徽标直接放置在屏幕中央,左右导航链接落在两侧。

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

所以,我的问题是,我怎样才能使徽标水平居中 - 死点 - 在屏幕上并且没有左右导航链接将徽标推离中心?

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

<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 允许每个项目增长(或缩小)而忽略其初始大小。这会在项目之间平均分配 space。使每个项目成为中心对齐的项目并分别使用 mr-automl-auto 均匀分配免费的 space。