Tailwind CSS Tutorial · Tailwind Basics · Lesson 6 of 27

Padding, Margin and Gaps

Adding space inside and around elements with padding, margin, space-between and gap utilities.

Create a free account to save this page, take notes and track your progress. Sign in

Padding and margin

Class Sides
p-4 / m-4 all four
px-4 / mx-4 left and right (x axis)
py-4 / my-4 top and bottom (y axis)
pt-4, pr-4, pb-4, pl-4 one side
ps-4, pe-4 start and end (flip automatically for right-to-left languages)
Margin vs paddingTry it yourself
<div class="p-6">
  <div class="inline-block bg-amber-200">
    <div class="m-4 bg-white p-6 ring-1 ring-amber-400">
      <span class="bg-sky-200">content</span>
    </div>
  </div>
  <p class="mt-3 text-sm text-gray-600">Amber shows the margin (m-4), white shows the padding (p-6).</p>
</div>

Space between children

space-y-4 puts space between stacked children; space-x-4 between children in a row. Inside flex and grid layouts, prefer gap-4, which also works when items wrap.

space-y and gapTry it yourself
<div class="grid gap-6 p-6 sm:grid-cols-2">
  <div class="space-y-3 rounded-lg border p-4">
    <p class="font-semibold">space-y-3</p>
    <div class="h-6 rounded bg-indigo-200"></div><div class="h-6 rounded bg-indigo-300"></div><div class="h-6 rounded bg-indigo-400"></div>
  </div>
  <div class="rounded-lg border p-4">
    <p class="mb-3 font-semibold">flex flex-wrap gap-2</p>
    <div class="flex flex-wrap gap-2">
      <span class="rounded-full bg-teal-100 px-3 py-1 text-sm">html</span><span class="rounded-full bg-teal-100 px-3 py-1 text-sm">css</span>
      <span class="rounded-full bg-teal-100 px-3 py-1 text-sm">tailwind</span><span class="rounded-full bg-teal-100 px-3 py-1 text-sm">javascript</span>
      <span class="rounded-full bg-teal-100 px-3 py-1 text-sm">accessibility</span>
    </div>
  </div>
</div>

Test yourself

Which class adds horizontal padding only?

  1. px-4
  2. py-4
  3. p-x-4
  4. padding-4
Show answer

Answer: px-4

x means the horizontal axis (left and right).

Was this page helpful?