skip to Main Content

I am using Tailwind to style my website.
As soon as I add gap-x-7 or bigger, the grid becomes bigger than the parent. It works fine for gap-x-6 or smaller. How can I fix this? Shouldn’t the col-span-6 always calculate the remaining width?

<div style="width: 300px" class="bg-red-400">
  <div class="grid grid-cols-12 gap-x-8">
    <div class="col-span-6 bg-blue-500">
      A
    </div>
    <div class="col-span-6 bg-green-500">
      B
    </div>
  </div>

  <div class="bg-yellow-500">
    It should be only this wide
  </div>
</div>

2

Answers


  1. Chosen as BEST ANSWER

    After playing around a little bit, I found out that the gap is added around every column even if they are only virtual. gap-x-7 or bigger will cause each column to be theoretically negative.

    To fix this problem, we need to divide the grid into fewer parts. In the following code, I replaced grid-cols-12 into grid-cols-2.

    <div style="width: 300px" class="bg-red-400">
      <div class="grid grid-cols-2 gap-x-8">
        <div class="col-span-1 bg-blue-500">
          A
        </div>
        <div class="col-span-1 bg-green-500">
          B
        </div>
      </div>
    
      <div class="bg-yellow-500">
        It should be only this wide
      </div>
    </div>
    

  2. I recommend using Flex instead of Grid. In CSS grid layouts, the gap property, which you’re using as gap-x, adds space between columns, and this space isn’t counted as part of the parent width, but the case is different in Flex. The first section in the image below shows the use of Flex, and the second shows the use of Grid:

    Flex and Grid usage

    <div style="width: 300px" class="bg-red-400">
        <div class="flex flex-row gap-x-8">
            <div class="flex-1 bg-blue-500">
                A
            </div>
            <div class="flex-1 bg-green-500">
                B
            </div>
        </div>
    
        <div class="bg-yellow-500">
            It should be only this wide
        </div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search