skip to Main Content

I know this quesion has been asked a lot of times. But they are all complex codes and the solutions differ based on their specific requirements.

Please run this very simple code on Tailwind Playground:

<div class="h-48 w-full bg-red-400">
  <a class="mx-auto inline-flex items-center bg-blue-400 px-8 py-5">Hello</a>
</div>

The a won’t be placed in the middle. The mx-auto does not work.

Can someone please tell me why it is so? And what should I do to put it in the middle.

P.S. I can not use text-center on the parent element.

2

Answers


  1. One cannot use margin-left: auto; margin-right: auto to center an inline element. To center it without using text-center on the parent, consider applying display: flex instead of display: inline-flex by changing the inline-flex class to flex and then either:

    Applying justify-content: center via justify-center to have the Hello text be centered:

    <script src="https://cdn.tailwindcss.com/3.3.3"></script>
    
    <div class="h-48 w-full bg-red-400">
      <a class="mx-auto flex items-center justify-center bg-blue-400 px-8 py-5">Hello</a>
    </div>

    Or width: max-content via w-max to have the <a> element itself be centered:

    <script src="https://cdn.tailwindcss.com/3.3.3"></script>
    
    <div class="h-48 w-full bg-red-400">
      <a class="mx-auto flex items-center w-max bg-blue-400 px-8 py-5">Hello</a>
    </div>
    Login or Signup to reply.
  2. The mx-auto class should work to center the element horizontally within its parent . However, there is a common issue that might prevent it from working as expected: the parent element must have a defined width for mx-auto to center its child element.

    In your code, the parent has a class of h-48 w-full bg-red-400, but w-full makes it take up the full width of its parent container. To use mx-auto effectively for centering, you should remove w-full or specify a fixed width for the parent . Here’s an updated version of your code with w-full removed:

    <div class="h-48 bg-red-400">
     <a class="mx-auto inline-flex items-center bg-blue-400 px-8 py-5">Hello</a>
    </div>
    

    Now, the element should be centered horizontally within the red . If you still encounter issues, please check if there are any conflicting CSS rules or styles that might be affecting the layout.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search