Spacing: the m and p classes
A utility is a small class that sets one CSS property. The most common utilities are spacing: m (margin, outer space) and p (padding, inner space). With them you rarely need your own CSS for distances between elements.
How to read a class
A class is made of three parts: property, side and size. mt-3 is margin-top of size three, px-2 is padding on the left and right of size two.
| Part | Values |
|---|---|
| Property | m — margin, p — padding |
| Side | t top, b bottom, s start (left), e end (right), x left and right, y top and bottom, no letter — all sides |
| Size | 0 = 0, 1 = 0.25rem, 2 = 0.5rem, 3 = 1rem, 4 = 1.5rem, 5 = 3rem, auto |
The letters s and e instead of left and right exist for right-to-left languages: there Bootstrap swaps the sides itself.
A first example
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="border p-4">1.5rem of padding inside</div>
<div class="border mt-3 px-5 py-1">1rem on top, 3rem on the sides</div>The first block keeps the same distance from its border on all sides. The second is pushed 1rem away from the first, and its text is close to the border at the top and bottom and far from it on the sides.
Centering and auto
mx-auto splits the free space on the left and right equally and centers a block that has a set width. ms-auto pushes an element to the right edge of a flex container:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="border p-3 mx-auto" style="max-width: 300px">Sign-in form</div>
<div class="d-flex border p-2 mt-3">
<span>Tasko</span>
<span class="ms-auto">Sign out</span>
</div>The form block is centered, and "Sign out" moves to the right. The d-flex class turns on flexbox; it is the topic of the next lesson.
Responsive spacing
A breakpoint name can go between the side letter and the size: p-2 p-md-5 means small padding on a phone and large from 768 pixels. This keeps landing page sections roomy on a laptop without wasting space on a phone.
Gap
For space between the children of a flex or grid container there is the gap-* class with the same scale:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="d-flex gap-2">
<button class="btn btn-primary">Save</button>
<button class="btn btn-outline-secondary">Cancel</button>
<button class="btn btn-outline-danger">Delete</button>
</div>The buttons are exactly 0.5rem apart, and you do not have to give each button its own margin.
Common mistake
Looking for mt-6 or p-10. The scale ends at 5 (3rem); there are no bigger numbers, and an unknown class simply does nothing. For bigger spacing write your own CSS or extend the scale with Sass — this is shown in the lesson on customizing Bootstrap with Sass.