Letting SASS build your utility classes

Written by Kevin Hougasian

We’ve moved around CSS frameworks in the past few years, Semantic UI for our application layer, and Bootstrap for our static sites. As our needs and applications continue to grow, we’re placing more demands on these frameworks and it can get a bit hacky.

We’re beginning to build our own framework, but there are parts of each we’d like to incorporate. Let’s look at spacers (margins and padding) first…

Looking at how bootstrap built their map, we added spacing closer to our needs:

$spacer: 1rem;
$spacers: (
  0: 0,
  1: ($spacer * .25),
  2: ($spacer * .5),
  3: $spacer,
  4: ($spacer * 2),
  5: ($spacer * 3),
  6: ($spacer * 4.5),
  7: ($spacer * 6.5)
);

We’re also also building utility classes for borders, so we’ll use that as well:

$xy-border: (
  top: t,
  right: r,
  bottom: b,
  left: l
);

Now let’s loop through both maps and add key value pairs for margin and padding:

// set key value pairs for margin and padding
@each $prop, $letter in (margin: m, padding: p) {

  // loop through top, right, bottom, and left
  @each $direction, $d in $xy-border {

    // loop through the spacers we've set
    @each $unit, $rem in $spacers {
      .#{$letter}#{$d}-#{$unit} {
        #{$prop}-#{$direction}: #{$rem};
      }

      // add in x-axis and y-axis spacing
      .#{$letter}x-#{$unit} {
        #{$prop}: 0 $rem;
      }
      .#{$letter}y-#{$unit} {
        #{$prop}: $rem 0;
      }
    }
  }
}

Nested looping has now generated 192 unique utility classes for us 😃. Here’s a Gist showing the output.

Published March 06, 2019 by

undefined avatar
Kevin Hougasian Lead Frontend Developer

Suggested Reading