EDIT: the wrong behavior was due to a missed </div>
(see screenshots).
Thank you so much for your patience -_-
I'm struggling with horizontal item centering in Tailwind CSS. Let's take a div with two children like so:
<div class="flex flex-row w-60 justify-center items-center space-x-10 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
and weirdly enough, it's not centered!
The problem, I found out, is that the x-spacing
is added between the two objects but is eating away at the space before the first object, so that the leftmost object gets "pushed" more to the left as space-x
increases.
This is centered:
<div class="flex flex-row w-60 justify-center items-center space-x-0 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
this is not:
<div class="flex flex-row w-60 justify-center items-center space-x-16 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
Does anyone know a solution to this? Is it a bug or am I just expecting the wrong behavior from justify-items
?
CodePudding user response:
Did you expected this?
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.15/tailwind.min.css" rel="stylesheet"/>
<div class="flex justify-between">
<div class="flex px-2 ">text 1</div>
<div class="flex px-2 ">text 2</div>
<div class="flex px-2 ">text 3</div>
</div>
If not, please describe in more detail what you expect the result to be!
CodePudding user response:
The problem lies with the use of w-60
which sets the <div>
to 15rem wide. This results in your two <p>
tags being centered inside the allowed 15rem, but since the <div>
is left-aligned, the items are not properly centered.
You can remove that class to center the two <p>
tags as required. Alternatively, you can add another <div>
tag with the w-60
class to get the centered effect you're after.
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.15/tailwind.min.css" rel="stylesheet"/>
<div class="w-60 bg-red-50">This div is 15rem wide</div>
<hr class="my-5">
<!-- 15rem container div -->
<div class="flex w-60 bg-red-50 justify-center items-center space-x-16 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
<hr class="my-5">
<!-- Additional div wrapper with the w-60 class applied. -->
<div class="w-60 mx-auto">
<div class="flex bg-red-50 justify-center items-center space-x-16 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
</div>
<hr class="my-5">
<!-- 100% wide container div -->
<div class="flex bg-red-50 justify-center items-center space-x-16 border-2">
<p>text 1</p>
<p>text 2</p>
</div>
The flex-row
class is redundant since it's the default behaviour, so I've removed it from the code.