Philipp Tuchardt / Bootstrap spacing

Created Sat, 01 Mar 2025 00:00:00 +0000

Understanding SCSS Spacers in Bootstrap

When working with Bootstrap, spacing is a crucial aspect of creating well-structured and visually appealing layouts. Bootstrap provides a flexible system for handling spacing using SCSS variables. In this article, we’ll explore the SCSS spacers in Bootstrap, how they work, and how you can use them effectively.

What Are SCSS Spacers?

Spacers in Bootstrap are predefined values used for margins (m-* classes) and paddings (p-* classes). These values are based on the $spacer variable and allow for a consistent spacing system across your project.

Here’s how Bootstrap defines the spacers:

$spacer: 1rem; // Default spacer (usually 16px)
$spacer-lg: $spacer * 2;   // 32px
$spacer-md: $spacer * 1.5; // 24px
$spacer-sm: $spacer * .5;  // 8px
$spacer-xs: $spacer * .25; // 4px

These values provide a range of spacing options, from extra small (xs) to large (lg).

Bootstrap’s $spacers Map

Bootstrap also uses a SCSS map to define spacing values dynamically. Here’s how it looks:

$spacers: (
  0: 0,
  1: $spacer * .25,  // 4px
  2: $spacer * .5,   // 8px
  3: $spacer,        // 16px
  4: $spacer * 1.5,  // 24px
  5: $spacer * 3     // 48px
) !default;

This map allows Bootstrap to generate utility classes such as:

  • .m-1margin: 4px;
  • .p-3padding: 16px;
  • .m-5margin: 48px;

How to Use Bootstrap Spacers in SCSS

1. Using SCSS Variables Directly

You can use the spacer variables directly in your styles:

.my-section {
  padding: $spacer-lg; // 32px padding
  margin-bottom: $spacer-sm; // 8px margin
}

2. Using `` to Retrieve Spacing Values

To fetch values from the $spacers map dynamically, use map-get:

.my-box {
  padding: map-get($spacers, 3); // Equivalent to $spacer (16px)
}

3. Generating Dynamic Spacing Classes

You can create a loop to generate custom spacing utility classes:

@each $key, $value in $spacers {
  .custom-m-#{$key} {
    margin: $value;
  }
  .custom-p-#{$key} {
    padding: $value;
  }
}

This will generate:

.custom-m-1 { margin: 4px; }
.custom-p-3 { padding: 16px; }

Why Use SCSS Spacers?

  • Consistency – Ensures uniform spacing across your project.
  • Customization – You can modify $spacer values to match your design system.
  • Efficiency – Reduces repetitive code and improves maintainability.

Conclusion

SCSS spacers in Bootstrap provide a powerful way to manage spacing efficiently. By using predefined variables and maps, you can maintain a consistent design while keeping your CSS clean and scalable. Whether using them directly in SCSS or leveraging Bootstrap’s utility classes, spacers help streamline your layout workflow.


Need a more customized spacing system? Modify the $spacer variable to suit your project’s requirements and generate your own custom spacing utilities! 🚀