Search code examples
reactjsjsxtailwind-csstailwind-ui

Why is w-fit making my navbar align to the left?


Im trying to centre my navbar which has a text logo and a logout button(hidden for current state). And i'm using a flex-col because I want my logout button and the logo to be vertically centered. I also want to use a black background for the nav, but the problem is that it spans the whole page, and i want it to stick to the content.

on using w-fit, the navbar goes to the left

    <div className="app ">
      <div className='w-fit'>
        <nav className="main-nav flex flex-col justify-center items-center h-24 bg-[#0D0D0D] p-12 rounded-full ">
        <Link to="/"><h1 className=' text-3xl font-display text-[#F2F2F2] p-12'>text-logo</h1></Link>
          {this.state.user &&
            <a href='#!' onClick={this.logOutUser}>Log out</a>
          }
          
        </nav>
      </div>

Solution

  • For pages displayed with left-to-right languages, such as English, elements will generally left align. As per MDN Documentation, (emphasis mine):

    The fit-content behaves as fit-content(stretch). In practice this means that the box will use the available space, but never more than max-content.

    Hence the <div> is left-aligned (as the default) with the content centered within. If you would like the <div> itself centered also, consider applying margin-left: auto; margin-right: auto to it via the mx-auto class:

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div class="app">
      <div class='w-fit mx-auto'>
        <nav class="main-nav flex flex-col justify-center items-center h-24 bg-[#0D0D0D] p-12 rounded-full ">
          <a to="/">
            <h1 class=' text-3xl font-display text-[#F2F2F2] p-12'>text-logo</h1>
          </a>
        </nav>
      </div>