Search code examples
csstailwind-css

Center Fixed Element in TailwindCSS


I have a flash message that appears when a page is loaded on successful auth and I'm trying to figure out how I can center it horizontally on any device. I am using the TailwindCSS to adjust the placement of the div and have tried fixed and absolute to make sure it appears above my content, but using an attribute like left:50% moves it too far over and margin:auto doesn't center this element. Is there a better approach to what I am trying to do? Is it possible to do with TailwindCSS or will I have to write some CSS for this?

Screenshot

Code:

<div>
    <div className="mx-auto sm:w-3/4 md:w-2/4 absolute" id="signin-success-message">
        <div className="bg-green-200 px-6 py-4 my-4 rounded-md text-lg flex items-center w-full">
            <svg viewBox="0 0 24 24" className="text-green-600 w-10 h-10 sm:w-5 sm:h-5 mr-3">
                <path fill="currentColor" d="M12,0A12,12,0,1,0,24,12,12.014,12.014,0,0,0,12,0Zm6.927,8.2-6.845,9.289a1.011,1.011,0,0,1-1.43.188L5.764,13.769a1,1,0,1,1,1.25-1.562l4.076,3.261,6.227-8.451A1,1,0,1,1,18.927,8.2Z"></path>
            </svg>
            <span class="text-green-800">{ body ? body : '' }</span>
        </div>
    </div>
    <div>
    ...
    </div>
</div>

Solution

  • use inset-x-0 with mx-auto

    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
    <div class="mx-auto sm:w-3/4 md:w-2/4 fixed inset-x-0 top-10" id="signin-success-message">
      <div class="bg-green-200 px-6 py-4 my-4 rounded-md text-lg flex items-center w-full">
        <svg viewBox="0 0 24 24" class="text-green-600 w-10 h-10 sm:w-5 sm:h-5 mr-3">
                    <path fill="currentColor" d="M12,0A12,12,0,1,0,24,12,12.014,12.014,0,0,0,12,0Zm6.927,8.2-6.845,9.289a1.011,1.011,0,0,1-1.43.188L5.764,13.769a1,1,0,1,1,1.25-1.562l4.076,3.261,6.227-8.451A1,1,0,1,1,18.927,8.2Z"></path>
                </svg>
        <span class="text-green-800">{ body ? body : '' }</span>
      </div>
    </div>

    To have vertical centring:

    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
    <div class="mx-auto sm:w-3/4 md:w-2/4 fixed inset-0 flex items-center" id="signin-success-message">
      <div class="bg-green-200 px-6 py-4 rounded-md text-lg flex items-center w-full">
        <svg viewBox="0 0 24 24" class="text-green-600 w-10 h-10 sm:w-5 sm:h-5 mr-3">
                    <path fill="currentColor" d="M12,0A12,12,0,1,0,24,12,12.014,12.014,0,0,0,12,0Zm6.927,8.2-6.845,9.289a1.011,1.011,0,0,1-1.43.188L5.764,13.769a1,1,0,1,1,1.25-1.562l4.076,3.261,6.227-8.451A1,1,0,1,1,18.927,8.2Z"></path>
                </svg>
        <span class="text-green-800">{ body ? body : '' }</span>
      </div>
    </div>