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
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
intogrid-cols-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: