简体   繁体   中英

How to horizontally center navbar content in Tailwind CSS

I recently began messing around with Tailwind & I decided that the first component would be a basic navbar with the following qualities.

  • Logo which should sit horizontally center of the screen
  • Navigation links on either side of the logo

Here's a simplified version of my attempt:

    <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>

My original approach was to have a flexbox container (nav) that would hold three divs, one for each section of the navbar, and to then use the justify-center class ( justify-content: center; ) to position the logo directly in the center of the screen, with the left & right navigation links falling on either side.

Once I tried this, I quickly found out that the justify-center class helped me position all of the divs and their content to the center of the screen along the container's axis. However, I didn't consider that the text on the right side of the logo is longer and thus pushes the logo slightly off-center to the left, relative to the center of the screen.

So, my question is, how can I center the logo horizontally - dead center - on the screen & not have the left or right navigation links push the logo off-center?

You can achieve it with the following:

 <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>

Giving each flex item flex-1 allows each item to grow (or shrink) while ignoring its initial size. This distributes the space equally between the items. Making each of the items a center justified item and using mr-auto and ml-auto respectively distributes the free space evenly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM