TailwindCSS: space-x or gap ?
A few weeks ago I had a discussion with a colleague about the eternal debate in frontend development: margins. This tweet reminded me of it.
More specifically the way we space things between each other. I’m using space-x-
and space-y-
all the time.
<div class="flex space-x-2">
<div>Something</div>
<div>Something else</div>
<div>...</div>
</div>
Over the years I’ve learned that it’s better to control the margins on a wrapping element here the div
element than to have the following:
<div class="flex">
<div>Something</div>
<div class="ml-2">Something else</div>
<div class="ml-2">...</div>
</div>
I find this example harder to read and more prone to forgetting an ml-2
. It’s also better to delegate the positioning to a higher-level element.
Issue with space-x- and space-y-
Things start to get messy when you want to change the flex-direction property. For example, with different directions based on breakpoints.
<div class="flex space-x-2 lg:flex-col">
<div>Something</div>
<div>Something else</div>
<div>...</div>
</div>
Here the margins are broken so you need a bit of adjustment.
<div class="flex space-x-2 lg:flex-col lg:space-x-0 lg:space-y-2">
<div>Something</div>
<div>Something else</div>
<div>...</div>
</div>
It’s starting to get unreadable. Other limitations are listed on the TailwindCSS documentation.
Solution: Gap
In recent years, modern browsers introduced a new CSS property: gap
which helps us solve the issue above.
<div class="flex gap-2 lg:flex-col">
<div>Something</div>
<div>Something else</div>
<div>...</div>
</div>
Problem solved.