About Lesson
Bootstrap5 Spacing
Bootstrap 5 provides spacing utilities to control margin (m-*) and padding (p-*) easily. These classes allow you to quickly add space around elements for better layout design.
1. Margin (m-*) and Padding (p-*) Classes
Bootstrap uses a scalable spacing system ranging from 0 (no space) to 5 (maximum space).
HTML
<div class="m-3 p-3 bg-primary text-white">Margin & Padding (3)</div>Output:
.m-3– Adds margin on all sides..p-3– Adds padding inside the element.
Available Sizes:
| Class | Space Value |
|---|---|
0 | No space |
1 | 4px |
2 | 8px |
3 | 16px |
4 | 24px |
5 | 48px |
auto | Auto Margin |
2. Spacing for Specific Sides
You can target specific sides using t (top), b (bottom), s (start/left), e (end/right), and x/y (horizontal/vertical).
HTML
<div class="mt-4 mb-2 me-3 ms-1 p-4 bg-secondary text-white">
Specific Side Spacing
</div>Output:
.mt-4– Margin-Top: 24px.mb-2– Margin-Bottom: 8px.me-3– Margin-End (Right): 16px.ms-1– Margin-Start (Left): 4px.p-4– Padding: 24px on all sides
3. Horizontal (mx-*) & Vertical (my-*) Spacing
For uniform spacing, Bootstrap provides mx-* for horizontal (left & right) and my-* for vertical (top & bottom) spacing.
HTML
<div class="mx-5 my-2 p-3 bg-success text-white">Horizontal & Vertical Spacing</div>Output:
.mx-5– Margin Left & Right: 48px.my-2– Margin Top & Bottom: 8px
4. Auto Margin (m-auto)
You can center elements using m-auto.
HTML
<div class="m-auto w-50 bg-warning text-dark text-center p-3">Centered Element</div>Output:
.m-auto– Auto margin for centering.w-50– 50% width to ensure centering works
5. Removing Spacing (m-0 and p-0)
Use 0 to remove margin or padding completely.
HTML
<div class="m-0 p-0 bg-danger text-white">No Margin & Padding</div>Output:
.m-0– Removes margin.p-0– Removes padding