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 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.
p-0
removes all padding for the element.p-1
applies level one padding equal to 1rem * .25
p-2
applies level two padding equal to 1rem * .5
p-3
applies level three padding equal to 1rem * 1
p-4
applies level four padding equal to 1rem * 1.5
p-5
applies level five padding equal to 1rem * 3.0
Here is an example of some padded elements
<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:
t
applies padding/margin to the top of the element.b
applies padding/margin to the bottom of the element.l
applies padding/margin to the left of the element.r
applies padding/margin to the right of the element.x
applies padding/margin to the x-axis of the element. (left and right)y
applies padding/margin to the y-axis of the element. (top and bottom)So an example would be:
<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
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.