Lesson 4: Spacing Utilities

Bootstrap contains a slew of shorthand spacing classes used to adjust margins and padding easily. The spacing sizes use rem heights ranging from .25 to 3. If you are not sure what rem is in CSS, the easy explanation is that rem sizes by the root html font element. So, if you set your base font size in your site to 16pt then the css 1rem would be the same as a 16pt font character. While the use of rem is not very exact, it does work very well.

Here's how spacing works in Bootstrap

Padding in Bootstrap

Padding in CSS is the space around an object between the contents and the outer edge of the element the padding is applied to. This is actually one of the things I started doing about 15 years ago with my own CSS - breaking up padding into common classes. It's a huge time-saver!

Bootstrap uses the letter p to specify padding. The following letters are used to denote the location of the padding.

Here is an example of some padded elements

This is padding level 1
This is padding level 2
This is padding level 3
This is padding level 4
This is padding level 5


<div class="container">
  <div class="row my-2">
    <div class="col-4 p-1">
      Level 1 padding
    </div>
  </div>
  
  <div class="row my-2">
    <div class="col-4 p-2">
      Level 2 padding
    </div>
  </div>
  
  <div class="row my-2">
    <div class="col-4 p-3">
      Level 3 padding
    </div>
  </div>
  
  <div class="row my-2">
    <div class="col-4 p-4">
      Level 4 padding
    </div>
  </div>
  
  <div class="row my-2">
    <div class="col-4 p-5">
      Level 5 padding
    </div>
  </div>
</div>


What if you want to apply padding to one or two sides? That is actually very simple.
You can specify a direction using this notation style: p{direction}-{size}. Directions are notated like this:

So an example would be:

A container with two rows seaprated by level 2 padding in the Y-axis.
A container with two rows seaprated by level 2 padding in the Y-axis.


<div class="container">
  <div class="row py-2">
    <div class="col-4">
    My column with py-2 padding on the row
    </div>
  </div>
  
  <div class="row py-2">
    <div class="col-4">
    My column with py-2 padding on the row
    </div>
  </div>
</div>


Personally, I prefer to set margins on my grid containers, rows, and columns instead of padding. Margins work the same way as padding, you just use the letter m instead of p. So, applying my-4 to a row will add level 4 margins to the top and bottom of the row element.

Here is an example of some elements using margins

This is margin level 1
This is margin level 2
This is margin level 3
This is margin level 4
This is margin level 5

As you can see, margins and padding are very simple in Bootstrap. Just remember the letter notation, placement notation, and that the numbers are not an exact measurement.