Home > OS >  Why is the first element of my tailwindcss grid slightly misaligned?
Why is the first element of my tailwindcss grid slightly misaligned?

Time:10-22

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 >
  <div >wood 1</div>
  <div >ore 2</div>
  <div >wood 3</div>
  <div >sheep 4</div>
  <div >wheat 5</div>
  <div >brick 6</div>
  <div >desert 7</div>
  <div >brick 8</div>
  <div >ore 9</div>
  <div >wood 10</div>
  <div >sheep 11</div>
  <div >wheat 12</div>
  <div >brick 13</div>
  <div >wood 14</div>
  <div >ore 15</div>
  <div >wheat 16</div>
  <div >sheep 17</div>
  <div >wheat 18</div>
  <div >brick 19</div>
</div>

CodePudding user response:

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).

CodePudding user response:

If you use grid, i will sugest to use gap-x-1 and gap-y-1.

And if you want margin top right left and bottom, you can use mt-1 ml-1 mr-1 mb-1

<!-- Tailwind 3 -->
<script src="https://cdn.tailwindcss.com"></script>


<!-- Body -->
<div >
  <div >wood 1</div>
  <div >ore 2</div>
  <div >wood 3</div>
  <div >sheep 4</div>
  <div >wheat 5</div>
  <div >brick 6</div>
  <div >desert 7</div>
  <div >brick 8</div>
  <div >ore 9</div>
  <div >wood 10</div>
  <div >sheep 11</div>
  <div >wheat 12</div>
  <div >brick 13</div>
  <div >wood 14</div>
  <div >ore 15</div>
  <div >wheat 16</div>
  <div >sheep 17</div>
  <div >wheat 18</div>
  <div >brick 19</div>
</div>

  • Related