Tailwind CSS Spacing
Tailwind uses a shorthand system to control padding and margin. By combining a prefix (p or m) with the various modifiers, you can precisely control the white space around your elements.
Most spacing utilities use a scale where each unit is 0.25rem (or 4px by default). For example, p-4 applies 1rem (16px) of padding on all sides. This consistent scale ensures that your layout remains proportional and visually harmonious.
Naming Convention
Spacing utilities follow a consistent naming pattern: {property}{side}-{size}.
| Prefix | Description |
|---|---|
p- |
Padding: Space inside an element. |
m- |
Margin: Space outside an element. |
space-x- |
Horizontal Space: Space between child elements. |
space-y- |
Vertical Space: Space between child elements. |
Side Modifiers
You can target all sides, a specific axis, or a single side using the modifiers below. For example, p- targets padding, while m- targets margin. You can then append a modifier to target specific sides:
| Modifier | Description | Tailwind Example | CSS Property |
|---|---|---|---|
| (none) | All sides | p-4 |
padding: 1rem; |
x |
Horizontal (Left & Right) | px-4 |
padding-left & -right |
y |
Vertical (Top & Bottom) | py-4 |
padding-top & -bottom |
t |
Top | mt-4 |
margin-top: 1rem; |
r |
Right | mr-4 |
margin-right: 1rem; |
b |
Bottom | mb-4 |
margin-bottom: 1rem; |
l |
Left | ml-4 |
margin-left: 1rem; |
Space Between
The space-x-{size} and space-y-{size} utilities can be used to add space between child elements. Instead of adding margins to every child item, you add these to the parent container. They automatically add space between the children, but skip the first or last child to avoid unwanted outer margins.
Here's an example of horizontal spacing:
Here's an example of vertical spacing:
Negative Margins & Arbitrary Values
To apply a negative margin, simply prefix the utility with a minus sign (e.g., -mt-8). For unique spacing needs, you can use arbitrary values, such as m-[13px].
Example
Next, we'll look at Sizing utilities for controlling the width and height of your elements.