Tip #1: Use space and gap utilities in TailwindCSS

  • — TailwindCSS

  • 1 min. read

  • — 2/12/2023

Spacing elements with margins and paddings is hard to read and hard to standardize. Instead, use Tailwind's built-in spacing utilities: space and gap.

Both utilities let you add spacing into a container in a clean and easy-to-read format. space-* utilities let you add spacing to elements by internally applying a margin-right or margin-top to children elements except for the first child element whereas gap-* leverages the native CSS gap property.

You can use space-* in any container to quickly add spacing between children elements. You can only use gap-* in flex and grid containers.

The available utilities are:

  • gap-*
  • gap-x-*
  • gap-y-*
  • space-*
  • space-x-*
  • space-y-*

Let's look at a practical example of this in action: let's say we're building a product card grid:

We need to add spacing to our product cards, we can do this by applying mr-4 to each product card individually or we can quickly add spacing by applying either space-x-4 or gap-x-4 to the container. Because we used a flex container, let's apply gap-x-4 (though you can apply space-x-4 and it would be the same):

Let's take a look at a quick example of using space and gap in the vertical direction:

Notice how much easier it is to read how spacing works, rather than children elements defining their spacing rules, you let the container define the spacing rules for its children elements. Now you only have to look in and modify one spot to change up how spacing works.

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!