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
One cannot use
margin-left: auto; margin-right: auto
to center an inline element. To center it without usingtext-center
on the parent, consider applyingdisplay: flex
instead ofdisplay: inline-flex
by changing theinline-flex
class toflex
and then either:Applying
justify-content: center
viajustify-center
to have the Hello text be centered:Or
width: max-content
viaw-max
to have the<a>
element itself be centered: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:
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.