Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • w-full: width: 100%
  • w-1/2 = width: 50%
  • w-1/3 = width: 33.33%
  • w-1-6 = width: 16.66%
  • gap-4 = gap: 16px
  • flex = display: flex
  • flex-wrap = flex-wrap: wrap;

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.

like image 923
Wiktor Kujawa Avatar asked Mar 21 '26 14:03

Wiktor Kujawa


1 Answers

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>
like image 182
whitespace Avatar answered Mar 23 '26 09:03

whitespace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!