Bootstrap Spacing

Bootstrap has a lot of features available for margins and padding. The various utility classes can be used to modify an element’s appearance.

How Bootstrap Spacing works

For a responsive-friendly margin or padding you need to assign the values to an element with the shorthand utility classes.

Bootstrap provides support for individual properties, vertical and horizontal properties and all properties.

The classes being used are built using a default Sass map that ranges from .25rem to 3rem.

Notation

The utility classes for spacing are applicable to all the breakpoints starting from xs and upto xl.

These classes have no breakpoint abbreviation in them. The reason being, these classes are applicable from the min-width value as 0 and upwards.

Therefore, they are not bound by any media query. However, there are breakpoint abbreviations available for the remaining breakpoints.

The naming format for these classes can be described as below:

  • {property}{sides}-{size} for xs
  • {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl

Here, the ‘property’ is replaceable with any of the following:

  • m – for classes responsible for setting the margin
  • p – for classes responsible for setting the padding

The ‘sides’ is replaceable with any of the following:

  • t – for classes responsible for setting margin-top or padding-top
  • b – for classes responsible for setting margin-bottom or padding-bottom
  • l – for classes responsible for setting margin-left or padding-left
  • r – for classes responsible for setting margin-right or padding-right
  • x – for classes responsible for setting both *-left and *-right
  • y – for classes responsible for setting both *-top and *-bottom
  • blank – for classes responsible for setting a margin or padding on all 4 sides of the element

The ‘size’ is replaceable with any of the following:

  • 0 – for classes responsible for eliminating the margin or padding by setting it to 0
  • 1 – (by default) for classes responsible for setting the margin or padding to $spacer * .25
  • 2 – (by default) for classes responsible for setting the margin or padding to $spacer * .5
  • 3 – (by default) for classes responsible for setting the margin or padding to $spacer
  • 4 – (by default) for classes responsible for setting the margin or padding to $spacer * 1.5
  • 5 – (by default) for classes responsible for setting the margin or padding to $spacer * 3
  • auto – for classes responsible for setting the margin to auto

More sizes can be added by adding entries to the $spacers Sass map variable.

See the code below for better understanding:

Examples

Bootstrap Horizontal Centering

For horizontal centering, Bootstrap provides the.mx-auto class.  

This justifies the fixed-width block level content or, in other words, the content that has display property set as block and width by setting the horizontal margins to auto.

The code snippet below illustrates the same: