bootstrap
  1. bootstrap-spacing-utilities

Bootstrap Spacing Utilities

Bootstrap provides various classes for adding spacing to elements, including margin and padding. These classes make it easy to create consistent spacing throughout your website.

Syntax

Bootstrap uses a specific naming convention for its spacing classes. Classes for margin and padding start with "m" and "p" respectively, followed by a hyphen and a value of 1 to 5, where 1 is the smallest and 5 is the largest. For example, m-4 adds a margin of 1.5rem to all sides of the element.

There are also classes that specify the direction of the margin or padding, such as ml-2 which adds a left margin of 0.5rem.

Example

Here's an example of how to use Bootstrap's spacing classes.

<div class="container">
  <div class="row">
    <div class="col-6 bg-secondary p-4">
      <h3 class="mt-4">First Column</h3>
      <p class="mb-4">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
    <div class="col-6 bg-primary p-4">
      <h3 class="mt-4">Second Column</h3>
      <p class="mb-4">Pellentesque ut lacus eget sem dictum pulvinar non at nisi.</p>
    </div>
  </div>
</div>
Try Playground

Explanation

In the code above, we used the following classes to apply the spacing:

  • container: this is a class applied to a container element that centers the content and adds some padding.
  • row: this class is used to create a row of columns within the container.
  • col-6: this class is used to create a column that spans 6 out of 12 columns in the row.
  • bg-primary and bg-secondary: these classes add a distinct background color to each column.
  • p-4: this class adds padding of 1.5rem to all sides of the column container.
  • mt-4 and mb-4: these classes add margin of 1.5rem to the top and bottom of the headings and paragraphs.

Use

Bootstrap's spacing utilities can be used to create consistent spacing between elements throughout your website. They're especially useful when creating responsive designs, where spacing needs to change depending on screen size.

Important Points

  • Bootstrap's spacing utility classes use a naming convention of "m" and "p", followed by a hyphen and a value of 1 to 5.
  • Classes for margin specify direction with prefixes such as "m-3" for margin of 1rem or "mt-3" for top margin of 1rem.
  • Padding classes follow the same pattern with prefix "p-", "pr-", "py-", etc. followed by value.
  • These classes make it easy to create consistent spacing between elements throughout your website.

Summary

Bootstrap's spacing utilities provide a convenient way to add consistent margin and padding to elements throughout your website. Using the naming convention, you can quickly add vertical or horizontal spacing, and specify it to specific directions with prefixes. These classes are especially useful when creating responsive designs.

Published on: