Spacing and Sizing
Padding, margin, gap, width, and height utilities, and the numeric scale they all share.
2 phút đọc
Padding, margin, gap, width, and height are the utilities you'll reach for most, and they all draw from the same shared numeric scale — learn the scale once and it applies everywhere.
The spacing scale
<div class="m-4 p-2">...</div>
<div class="mt-8 mb-2 px-6">...</div>Each step in Tailwind's default spacing scale is a multiple of 0.25rem (4px at the default browser font size): 1 is 0.25rem, 2 is 0.5rem, 4 is 1rem, 8 is 2rem, and so on. So p-2 is padding: 0.5rem, and mt-8 is margin-top: 2rem. The scale isn't linear in "one unit = one pixel" — it's linear in quarter-rems, which is fine-grained at the small end (where visual differences matter most) and coarser at the large end.
Directional and axis shorthands
You rarely need to set all four sides of padding or margin the same way, so Tailwind gives you directional and axis variants:
<div class="px-4 py-2">...</div> <!-- padding-left/right, padding-top/bottom -->
<div class="mt-4 mr-2 mb-4 ml-2">...</div> <!-- one side each -->
<div class="-mt-2">...</div> <!-- negative margin -->px-* and py-* set both sides of an axis at once — the most common case by far, since horizontal and vertical padding are usually set independently of each other rather than all four sides individually. A leading - produces a negative value, useful for pulling an element outside its normal box (overlapping an avatar over a banner image, for example).
Gap, for spacing between children
gap is arguably more useful than margin in a flex or grid layout, because it spaces items between each other without adding space around the outer edge of the group:
<div class="flex gap-4">
<div class="rounded bg-slate-100 p-3">One</div>
<div class="rounded bg-slate-100 p-3">Two</div>
<div class="rounded bg-slate-100 p-3">Three</div>
</div>If you used mr-4 on each child instead, the last child would carry a trailing margin you'd have to remove with a special case. gap-4 avoids that entirely — it only ever applies between items.
Width and height
<img class="h-12 w-12 rounded-full" src="/avatar.jpg" alt="" />
<div class="w-full max-w-md">...</div>
<div class="h-screen">...</div>w-12/h-12 use the same numeric scale as spacing. Beyond the numeric scale, Tailwind provides useful named sizes: w-full (100%), w-screen (100vw), h-screen (100vh), and fractional widths like w-1/2 or w-1/3 for simple proportional layouts without flexbox or grid.
Why a shared scale matters
The real benefit isn't any single class — it's that gap-4, p-4, and mt-4 all produce the same 1rem. When every spacing decision in a codebase is pulled from one shared scale instead of freehand pixel values, a page tends to look consistent almost by default, even across components built by different people at different times.