Search code examples
cssflexboxtailwind-csstailwind-css-2

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

  • 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>