Bootstrap ยท Chapter 36 of 43

Bootstrap Spacing Utilities

Spacing utility classes let you add margin and padding to elements directly through class names, following the pattern {property}{sides}-{size}, such as mt-3 for margin-top or px-2 for horizontal padding.

The size scale runs from 0 (no spacing) to 5 (largest spacing), plus an 'auto' value for margins, which is commonly used to center block elements horizontally.

Syntax
<div class="mt-3 px-2 mb-4">...</div>

Margin and padding classes

m stands for margin and p for padding. Sides are t (top), b (bottom), s (start/left), e (end/right), x (left and right), y (top and bottom), or blank for all sides.

The spacing scale

Sizes range from 0 to 5, each roughly representing a multiple of 0.25rem to 3rem. mx-auto is a special value that centers a block-level element with a defined width.

Example 1 (html)
<div class="p-4 mb-3 bg-light">Padding on all sides, margin below</div>
<div class="p-4 bg-secondary text-white">Second box</div>
Output
Two boxes with visible internal padding and a gap between them

p-4 adds padding inside the box, and mb-3 adds margin below it, creating spacing between the two boxes.

Example 2 (html)
<div class="mx-auto bg-info" style="width: 200px;">Centered box</div>
Output
A 200px-wide box centered horizontally in its container

mx-auto sets left and right margins to auto, which centers a block element with a fixed width.

Key points

  • m = margin, p = padding, following {property}{side}-{size}.
  • Sides: t (top), b (bottom), s (start), e (end), x (horizontal), y (vertical).
  • Sizes range from 0 (none) to 5 (largest).
  • mx-auto centers a fixed-width block element horizontally.
๐Ÿ’ก Note: Prefer spacing utility classes over custom CSS margins/padding to keep spacing consistent across your site.

๐Ÿ“ Quick Quiz

1. What does the class 'mt-3' apply?

2. Which class centers a fixed-width block horizontally?

3. Which side abbreviation means horizontal (left and right)?