Spacing: Margin & Padding Utilities

Bootstrap Framework 10 min min read Updated: Nov 16, 2026 Beginner
Spacing: Margin & Padding Utilities
Beginner Topic 4 of 11

Margin vs Padding

These two words confuse many beginners, so remember this picture:

  • Margin is the space outside an element, between it and its neighbors
  • Padding is the space inside an element, between its border and its content
Simple example: Think of a framed photo on a wall. Margin is the distance between frames on the wall. Padding is the white border inside the frame around the photo.

The Naming Pattern

The class name follows this pattern: {property}{side}-{size}

PartOptions
Propertym = margin, p = padding
Sidet top, b bottom, s start (left), e end (right), x left and right, y top and bottom, (nothing) all four sides
Size0, 1, 2, 3, 4, 5, and auto for margin

Sizes

NumberSpace
00
10.25rem (4px)
20.5rem (8px)
31rem (16px)
41.5rem (24px)
53rem (48px)

Examples

html <div class="p-3">Padding on all sides</div> <div class="m-4">Margin on all sides</div> <div class="mt-5">Margin only on top</div> <div class="mb-2">Margin only on bottom</div> <div class="px-4">Padding left and right</div> <div class="py-2">Padding top and bottom</div>

Centering with Auto Margin

html <div class="w-50 mx-auto border p-3"> I am centered horizontally. </div>

mx-auto sets both left and right margins to auto, which centers a box that has a fixed or limited width. ms-auto pushes an element to the right.

Responsive Spacing

html <div class="p-2 p-md-4 p-lg-5"> Small padding on phones, bigger on larger screens. </div>

Gap

Use gap-* on flex or grid containers to add space between children without margins.

html <div class="d-flex gap-3"> <button class="btn btn-primary">One</button> <button class="btn btn-secondary">Two</button> </div>

Negative Margins

Negative margin classes use an n before the size, such as mt-n1. They are not enabled by default and need the Sass option to be turned on, so beginners rarely use them.

Common Mistakes

  • Mixing up margin and padding
  • Using left and right (ml, mr), which were Bootstrap 4 names. In Bootstrap 5 use ms and me
  • Using mx-auto on an element that takes the full width, where nothing visibly changes
Practice: Create three boxes with bg-light border and apply p-1, p-3, p-5 on them. Then try m-1, m-3, m-5 and see the difference.

Conclusion

Spacing classes are used in nearly every Bootstrap project. Learn the {property}{side}-{size} pattern, and you can space anything quickly.

Quick Summary: m = margin, p = padding, t/b/s/e/x/y for sides, sizes 0 to 5 and auto. Use breakpoints for responsive spacing.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators