Spacing elements with margins and paddings is hard to read and hard to standardize. Instead, use Tailwind's built-in spacing utilities:
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
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:
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
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
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.