
Tailwind is an awesome resource when styling web applications. It’s fast, lightweight, and easy to use once you get used to the class-first syntax. But what do you use when you need to add some spacing between items — gap or space?
Let’s get into it.
What do I use?
To tackle this question, let’s create a scenario. We’ll be using three boxes represented by divs
in an HTML document.
<section>
<div class="w-48 h-48 bg-slate-300">Box 1</div>
<div class="w-48 h-48 bg-slate-400">Box 2</div>
<div class="w-48 h-48 bg-slate-500">Box 3</div>
</section>
In this example, there are three boxes we need to add some spacing to. Normally, the way to go about this would be to:
But what happens when there’s no need to use a flex layout or margin? What do we use?
That’s where the space Tailwind class comes in. Picture it as what gap
is capable of in a grid or flex layout, but without the flex/grid. So let's see a side-by-side comparison.
<!-- with tailwind space -->
<section class="space-5">
<div class="w-48 h-48 bg-slate-300">Box 1</div>
<div class="w-48 h-48 bg-slate-400">Box 2</div>
<div class="w-48 h-48 bg-slate-500">Box 3</div>
</section>
<!-- with tailwind gap -->
<section class="flex gap-5">
<div class="w-48 h-48 bg-slate-300">Box 1</div>
<div class="w-48 h-48 bg-slate-400">Box 2</div>
<div class="w-48 h-48 bg-slate-500">Box 3</div>
</section>
In the first code block, using Tailwind space
creates spacing between the items in the section element. The main difference is that when using gap
, a flex or grid layout is required, whereas when using space
, it's not.
This is something I discovered earlier when exploring more of what Tailwind CSS can do in my projects.
Hopefully, this article has helped to simplify the gap vs. space concept in Tailwind. For more detailed documentation, please visit the official Tailwind docs: Tailwind gap vs. Tailwind space.
Thanks for reading, and have a great day.
Ciao