Lesson 27 +10 XP

Margin & Padding

Margin & Padding

Spacing utilities control the space around and inside elements. In v4 the spacing scale is dynamic: every integer maps to calc(var(--spacing) * n).

The spacing scale

--spacing defaults to 0.25rem (4px). So:

  • p-1 = 4px, p-2 = 8px, p-4 = 16px, p-6 = 24px, p-8 = 32px.
  • Any integer works, including p-13, p-96, p-100.

Padding

ClassCSS
p-<n>all sides
px-<n>left + right
py-<n>top + bottom
pt-<n>, pr-<n>, pb-<n>, pl-<n>single sides
<button class="px-4 py-2">Padding</button>

Margin

Same pattern as padding:

ClassCSS
m-<n>all sides
mx-<n>left + right
my-<n>top + bottom
mt-<n>, mr-<n>, mb-<n>, ml-<n>single sides

Negative margins

Prefix with a minus sign:

<div class="-mt-6">Overlaps the element above</div>

Auto margins

m-auto, mx-auto, mt-auto, etc.:

<div class="mx-auto max-w-md">Centered horizontally</div>

mt-auto pushes an item to the bottom of a flex column.

Special values

px, py, mx, my without a number are NOT valid (unlike size); always include a number or auto.

TL;DR

  • p-4 = 1rem padding; m-4 = 1rem margin.
  • px/py for axes, pt/pb/ml etc. for sides.
  • Negative: -mt-6.
  • mx-auto centers block elements.