Now, in this lesson, we’ll focus on one of the most important foundations in Tailwind:
Spacing & Sizing: margin, padding, width, and height.
Understanding spacing is key to building clean, balanced, and beautiful layouts. Let’s dive in!
Tailwind provides short, simple classes that describe exactly what spacing or size you want:
| Property | Meaning |
|---|---|
m | margin |
p | padding |
w | width |
h | height |
These are followed by a number. For example:
| Class | Meaning |
|---|---|
m-4 | margin = 1rem (16px) |
p-6 | padding = 1.5rem (24px) |
w-1/2 | width = 50% |
h-10 | height = 2.5rem (40px) |
Tailwind uses a spacing scale like this:
1 → 4px2 → 8px3 → 12px4 → 16px5 → 20px6 → 24px...
So p-4 means padding: 16px
m) and Padding (p)<div class="m-4 p-4 bg-gray-200">This box has margin and padding.</div>
| Class | Meaning |
|---|---|
mt-4 | margin-top: 16px |
mb-6 | margin-bottom: 24px |
ml-2 | margin-left |
mr-2 | margin-right |
mx-4 | margin left & right |
my-8 | margin top & bottom |
Examples:
<p class="mt-6">Margin top only</p><p class="mx-4">Margin left & right</p>
p) works the same way| Class | Meaning |
|---|---|
p-6 | padding all sides |
px-4 | padding left & right |
py-8 | padding top & bottom |
Example:
<button class="px-6 py-3 bg-blue-500 text-white rounded">Button with padding</button>
w) and Height (h)Tailwind gives multiple sizing options:
<div class="w-32 h-16 bg-green-300"></div>
w-32 = 8rem (128px)h-16 = 4rem (64px)<div class="w-1/2 bg-red-300">50% width</div>
<div class="w-full">Full width</div><div class="h-screen">Full screen height</div>
Here’s a great example combining spacing + sizing:
<div class="max-w-sm p-6 bg-white rounded shadow"><h2 class="text-xl font-bold mb-4">Tailwind Spacing Demo</h2><p class="mb-6 text-gray-600">Using margin and padding helps create cleaner layouts.</p><button class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded">Learn More</button></div>
What you learned from this example:
p-6 → Inside space for contentmb-4, mb-6 → Space between elementsAfter this lesson, you now understand how to control spacing and sizing using Tailwind:
| Concept | Example Class | Meaning |
|---|---|---|
| Margin | mt-4, mx-6 | Adjust external spacing |
| Padding | py-4, px-8 | Adjust inner spacing |
| Width | w-full, w-1/2 | Control size horizontally |
| Height | h-10, h-screen | Control vertical size |
Mastering spacing is the key to making professional designs.