Wiktor Kujawa
Wiktor Kujawa

Reputation: 507

CSS Flex layout and gap(tailwind example)

Let's say, that we have this design:

<div className="w-full flex flex-wrap gap-4">
  <div className="w-1/2"></div>
  <div className="w-1/3"></div>
  <div className="w-1/6"></div>
</div>

If you don't know tailwind, no problem:

Now, let's go to the problem. I want these three divs to be in one row( because 50% + 33.33% + 16.66% = 100%) and it's working without a gap, but when I add a gap, it's collapsing due to the gap increasing the space of layout. In the more complex layout, there will be more boxes, with the width being multiple of w-1/6( w-1/3, w-1/2, w-2/3, w-5/6, w-full). How to achieve equal gap without increasing the space, to not wrap, because of gap.

Upvotes: 3

Views: 2532

Answers (2)

Ihar Aliakseyenka
Ihar Aliakseyenka

Reputation: 14313

Use flex property instead of width

<div class="w-full flex flex-wrap gap-4">
  <div class="flex-[3]"></div>
  <div class="flex-[2]"></div>
  <div class="flex-1"></div>
</div>

DEMO

For demonstration purposes I've created a solution for grid layout - the result will differ slightly because gap for grid included within div element

Upvotes: 0

whitespace
whitespace

Reputation: 324

This is due to the fact how the box model works: Gap is added to the width of the box.

You can, however, achieve your desired result by:

  • adding padding to each individual element
  • removing the padding on the parent container using negative margins
<div class="-mx-2 flex flex-wrap">
  <div class="w-1/2 px-2">A</div>
  <div class="w-1/3 px-2">B</div>
  <div class="w-1/6 px-2">C</div>
</div>

Upvotes: 1

Related Questions