DEV Community

Cover image for TW Elements - Spacing. Free UI/UX design course
Keep Coding
Keep Coding

Posted on

TW Elements - Spacing. Free UI/UX design course

Spacing

The elements in Call to action are very close to each other, which makes them seem squeezed. I don't know about you, but I have the impression that they are asking for some space and breath.

Image description

This is exactly what Tailwind's spacing utilities classes are for - they allow us to offset elements in 4 directions - up, down, left and right.

Thanks to spacing utilities we can easily manipulate padding and margin of any element. For example, if you want to add a bottom margin to an h1 element you can add class mb- ("m" for "margin" and "b" for "bottom") to it and choose a unit between 0.5 to 96.

mb-0.5: sets margin-bottom to 0.125rem (2px)

mb-96: sets margin-bottom to 24rem (384px)

Step 1 - add margin bottom to the headings

Let's add .mb-5 to h1 and .mb-7 to h2:

<!-- Call to action -->
<div class="text-center text-white">
  <h1 class="mb-5 text-5xl font-semibold">I am learning Tailwind</h1>
  <h2 class="mb-7 text-2xl font-medium">
    And what an exciting adventure it is!
  </h2>
</div>
Enter fullscreen mode Exit fullscreen mode

Now they can breathe freely!

Notice that we added a bottom margin to the h2 element as well, even though there is nothing underneath it. However, that will soon change as we will add a button there.

How spacing works in Tailwind CSS

You may have guessed that if you need to use the mb-* class to add a bottom margin, you need to add the mt-* class to add a top margin. And you will be right.

The same applies to the left and right margins - we use the ms-* and me-* classes respectively

For example:

mt-8 to add some margin to the top

ms-2 to add some margin to the left

me-4 to add some margin to the right

How to use padding

It's easy. The same scheme for margins applies to padding - so for example, .pt-4 to add some top padding, ps-5 to add some left padding, and so on.

Below is an example using classes for the right margin with a visual representation of their sizes. The same sizes apply to all directions (left, right, top, bottom) and for both margins and padding.

Image description

DEMO AND SOURCE CODE FOR THIS LESSON

Top comments (0)