Using Sass' @each and @for for Bootstrap-Like Behavior of Margin & Padding Classes

Ria Pacheco - Apr 29 '22 - - Dev Community

Bootstrap Backgrounder

Bootstrap includes margin and padding functionality that allows you to decide on what side of the element the margin or padding should be applied and how much of it should be layered on (multiple of the base font-size).

This means that if on an element you'd like to add padding to the top by 3 multiples of the base font-size, it'll add 45px of padding to the top of the element [base font size 15 x 3 = 45px] and is done with the class pt-3.

Problem

I don't like using Bootstrap libs since they restrict design, but I want the same class functionality that's used for margin and padding adjustments from directly within the HTML element.


Sass' @each and @for Features

If you're a .scss fan (css extension), then you can add the @each and @for methods to a global stylesheet for this same behavior:

// Margin
@each $abbr, $name in ("t": "top", "r": "right", "b": "bottom", "l": "left") {
  @for $i from 1 through 20 {
    .m#{$abbr}-#{$i} {
      margin-#{$name}: 1rem * $i;
    }
  }
}

// Padding
@each $abbr, $name in ("t": "top", "r": "right", "b": "bottom", "l": "left") {
  @for $i from 1 through 20 {
    .p#{$abbr}-#{$i} {
      padding-#{$name}: 1rem * $i;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What's going on here?

  • Defined abbreviations associated to full words in an array
  • Defined limits of multiple (1 to 20)
  • Applied with template literals where abbreviation pairs should be applied along with the multiple
. . . . . . . . . . . . . . . . .