Issue
I'm using Tailwind CSS to make a grid. In the parent div, I'm using the classes space-x-1
and space-y-1
to automatically align the child divs.
This works well except the first element is slightly misaligned. The first element has a computed margin of 0, while every other element has a computed margin of 4px. When I remove the space-x-1
and space-y-1
from the parent div, the child divs have the same margins.
<!-- Tailwind 3 -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Body -->
<div class="grid grid-cols-5 space-x-1 space-y-1">
<div class="text-white text-center p-2 bg-green-700">wood 1</div>
<div class="text-white text-center p-2 bg-gray-700">ore 2</div>
<div class="text-white text-center p-2 bg-green-700">wood 3</div>
<div class="text-white text-center p-2 bg-purple-800">sheep 4</div>
<div class="text-white text-center p-2 bg-yellow-500">wheat 5</div>
<div class="text-white text-center p-2 bg-yellow-900">brick 6</div>
<div class="text-white text-center p-2 bg-pink-700">desert 7</div>
<div class="text-white text-center p-2 bg-yellow-900">brick 8</div>
<div class="text-white text-center p-2 bg-gray-700">ore 9</div>
<div class="text-white text-center p-2 bg-green-700">wood 10</div>
<div class="text-white text-center p-2 bg-purple-800">sheep 11</div>
<div class="text-white text-center p-2 bg-yellow-500">wheat 12</div>
<div class="text-white text-center p-2 bg-yellow-900">brick 13</div>
<div class="text-white text-center p-2 bg-green-700">wood 14</div>
<div class="text-white text-center p-2 bg-gray-700">ore 15</div>
<div class="text-white text-center p-2 bg-yellow-500">wheat 16</div>
<div class="text-white text-center p-2 bg-purple-800">sheep 17</div>
<div class="text-white text-center p-2 bg-yellow-500">wheat 18</div>
<div class="text-white text-center p-2 bg-yellow-900">brick 19</div>
</div>
Solution
Instead of using space-x-1
and space-y-1
, you should use gap-1
, which is meant to be used with grid and flex layouts. It adds a gap between your items without the unwanted side margins. You can also use gap-x-1
and gap-y-1
individually.
The space-
classes are meant for horizontal or vertical layouts only. It adds space to all items except the first one, to prevent an unwanted space at the start (which is why your first item is misaligned).
Answered By - J-P-Robin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.