
Margin And Padding in TailwindCSS
? Margin and Padding Utilities in Tailwind CSS
Tailwind makes it simple to control margin and padding with easy-to-use utility classes. These apply spacing outside (margin) or inside (padding) of elements.
1. Margin (m
)
Controls the outer space around an element.
Class Example | CSS Equivalent | Description |
---|---|---|
m-4 | margin: 1rem; | Margin on all sides |
mt-2 | margin-top: 0.5rem; | Top margin |
mr-6 | margin-right: 1.5rem; | Right margin |
mb-1 | margin-bottom: 0.25rem; | Bottom margin |
ml-3 | margin-left: 0.75rem; | Left margin |
mx-5 | margin-left/right: 1.25rem; | Horizontal margins |
my-2 | margin-top/bottom: 0.5rem; | Vertical margins |
-m-2 | margin: -0.5rem; | Negative margin (all sides) |
2. Padding (p
)
Controls the inner space between content and border.
Class Example | CSS Equivalent | Description |
---|---|---|
p-4 | padding: 1rem; | Padding on all sides |
pt-2 | padding-top: 0.5rem; | Top padding |
pr-6 | padding-right: 1.5rem; | Right padding |
pb-1 | padding-bottom: 0.25rem; | Bottom padding |
pl-3 | padding-left: 0.75rem; | Left padding |
px-5 | padding-left/right: 1.25rem; | Horizontal padding |
py-2 | padding-top/bottom: 0.5rem; | Vertical padding |
3. Spacing Scale
Tailwind uses a default spacing scale based on rems (1rem = 16px by default):
Class Value | rem | px |
---|---|---|
0 | 0 | 0 |
0.5 | 0.125 | 2 |
1 | 0.25 | 4 |
1.5 | 0.375 | 6 |
2 | 0.5 | 8 |
2.5 | 0.625 | 10 |
3 | 0.75 | 12 |
3.5 | 0.875 | 14 |
4 | 1 | 16 |
5 | 1.25 | 20 |
6 | 1.5 | 24 |
7 | 1.75 | 28 |
8 | 2 | 32 |
9 | 2.25 | 36 |
10 | 2.5 | 40 |
4. Example Usage
<div class="m-6 p-4 bg-blue-200"> <p class="mb-2">This box has margin 1.5rem and padding 1rem.</p> <button class="px-3 py-1 bg-blue-500 text-white rounded">Button</button></div>
5. Negative Margins
Sometimes you need to pull elements closer or overlap.
<div class="relative"> <div class="bg-gray-300 p-6">Normal content</div> <div class="-mt-4 bg-red-400 p-4">Pulled up with negative margin-top</div></div>
If you want, I can also explain how to customize the spacing scale or show responsive margin/padding examples!