'Tailwind: add gap to flex without breaking row

I have a simple flex div with many children. I want 3 elements on each row using tailwindcss.

Is there a way to accomplish this using just tailwindcss classes? I tried with gap-4 on my parent div and child elements with w-1/3, but it adds margin to the children elements, breaking the row after the second element:

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.7/tailwind.min.css" rel="stylesheet"/>
<div class="flex flex-wrap gap-4  mb-6">
        <div class="w-1/3 shadow border rounded p-4">
            My element
        </div>
        <div class="w-1/3 shadow border rounded p-4">
            My element
        </div>
        <div class="w-1/3 shadow border rounded p-4">
            My element
        </div>
        <div class="w-1/3 shadow border rounded p-4">
            My element
        </div>
    </div>

How can I add a gap between the child elements, breaking the line only after every third element (in short: I want a 3 column div)?



Solution 1:[1]

This is a grid job

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.7/tailwind.min.css" rel="stylesheet"/>
<div class="grid-cols-3 grid gap-4  mb-6">
        <div class="shadow border rounded p-4">
            My element
        </div>
        <div class="shadow border rounded p-4">
            My element
        </div>
        <div class="shadow border rounded p-4">
            My element
        </div>
        <div class="shadow border rounded p-4">
            My element
        </div>
    </div>

Solution 2:[2]

You also can use the space between utility space-x-{amount} if you want to keep using flex instead of grid:

<div class="flex space-x-4 ...">
  <div>01</div>
  <div>02</div>
  <div>03</div>
</div>

More details here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Temani Afif
Solution 2 Fabio Zanchi