Bootstrap Spacing: Margin, Padding and Gap

Spacing classes are the most used Bootstrap utilities. You can add margin (outside space) and padding (inside space) to any element, without writing CSS.

The naming

{property}{sides}-{size}
{property}{sides}-{breakpoint}-{size}

property: m (margin) or p (padding)
sides:    t (top), b (bottom), s (start/left), e (end/right), x (left and right), y (top and bottom), blank (all sides)
size:     0, 1, 2, 3, 4, 5, auto
SizeValue (with the default font size)
00
10.25rem (4px)
20.5rem (8px)
31rem (16px)
41.5rem (24px)
53rem (48px)
autoauto (for margin only)

Examples

<div class="bg-body-secondary p-3 mb-3">p-3: padding on all sides</div>
<div class="bg-body-secondary px-5 py-1 mb-3">px-5 py-1: more padding left and right</div>
<div class="bg-body-secondary mt-4 mb-1 ps-4">mt-4 mb-1 ps-4</div>
Live preview

Auto margin: center and push

<div class="bg-primary-subtle mx-auto mb-2" style="width: 150px">mx-auto (centered)</div>
<div class="d-flex bg-body-secondary">
  <div class="p-2 bg-warning-subtle">Item</div>
  <div class="p-2 ms-auto bg-info-subtle">ms-auto (pushed to the right)</div>
</div>
Live preview

Responsive spacing

Add a breakpoint to use a different space on bigger screens: p-2 p-md-4 means padding 2 on small screens and padding 4 from 768px.

<div class="bg-body-secondary p-2 p-md-5 mb-2">p-2 p-md-5</div>
Live preview

Gap

In flex and grid containers, gap-* (and row-gap-*, column-gap-*) sets the space between the children, so you do not need margins on each of them.

<div class="d-flex gap-3">
  <div class="p-2 border">One</div>
  <div class="p-2 border">Two</div>
  <div class="p-2 border">Three</div>
</div>
Live preview

Negative margins and the old classes

  • Negative margins are off by default. They can be turned on with the Sass variable $enable-negative-margins.
  • .ml-* and .mr-* of Bootstrap 4 are now .ms-* and .me-* (start and end), so they also work in right to left languages.
Note: Margins between elements collapse in the vertical direction in the normal flow, but not in flex and grid. This is a normal CSS behavior and is not a bug of Bootstrap. Next: Flex Utilities.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.