Sass Loops for Creating Custom Utility Classes

Here, we define margin and padding that we'd like to use with $increments and then directions using $directions, e.g. margin-top: ....

/**
* Margin and padding utility classes
* Utility class, add !important
*/

// Define increments (pixels) and directions needed.
$increments: (4, 8, 12, 16, 20, 24, 32, 40, 48, 56, 64, 72, 80, 88, 102, 118, 124, 136, 148);
$directions: (top, bottom);

// Loop through the increments and directions.
@each $increment in $increments {
  @each $direction in $directions {
    .m#{str-slice($direction, 0, 1)}-#{$increment} {
      margin-#{$direction}: #{$increment}px !important;
    }

    .p#{str-slice($direction, 0, 1)}-#{$increment} {
      padding-#{$direction}: #{$increment}px !important;
    }
  }
}

The resulting CSS generated is:

.mt-4 {
  margin-top: 4px !important;
}

.pt-4 {
  padding-top: 4px !important;
}

.mb-4 {
  margin-bottom: 4px !important;
}

.pb-4 {
  padding-bottom: 4px !important;
}

etc...