Space vs. Gap — Tailwind CSS Explained

Space vs. Gap — Tailwind CSS Explained

posted Originally published at medium.com 2 min read


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:

  • Use a flex layout on the section parent element and add a gap value to create space.

  • Use a margin on each box.

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 spacecreates 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

If you read this far, tweet to the author to show them you care. Tweet a Thanks

Nice breakdown of the gap vs. space classes — it’s a small detail but makes a big difference when structuring layouts. In what ways do you think using space over gap could simplify styling in larger projects?

More Posts

CSS Specificity Explained: How to Control Which Styles Win

Bridget Amana - Dec 19, 2024

A module for a hexagonal masonry layout with CSS and JavaScript

Ingo Steinke - Oct 1

Still.js - A way to leverage Vanilla JavaScript for Complex and Enterprise Level Web Development

Nakassony Bernardo - Jun 29

em is a relative unit based on the parent element’s font size.

Dr Prime - Apr 16

Top UI Libraries to Win Your Next Hackathon

harshit_rwt - Jan 27
chevron_left