Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Real-world Patterns

Utility Class Generators with Sass Loops

Generate utility classes with Sass maps, @each and @for: spacing scales, color helpers, responsive variants, a 12-column grid and an API map, while keeping output size under control.

A utility class does one thing: .mt-2 { margin-top: 0.5rem; }, .text-center, .bg-primary. Frameworks like Bootstrap and Tailwind popularized them because they let you style in markup without inventing a name for every element. Writing hundreds of such classes by hand is tedious and error-prone, but loops generate them from a few lines of data. This is the classic showcase for Sass control directives.

The same techniques apply to anything repetitive: color helpers, grid columns, z-index layers, aspect ratios. The skill to practice is describing the data once and letting the compiler do the typing.

Starting small: a spacing scale

SCSS
$spacing: (0: 0, 1: 0.25rem, 2: 0.5rem, 3: 1rem, 4: 1.5rem, 5: 3rem);

@each $key, $value in $spacing {
  .m-#{$key}  { margin: $value; }
  .mt-#{$key} { margin-top: $value; }
  .p-#{$key}  { padding: $value; }
  .pt-#{$key} { padding-top: $value; }
}

@each $key, $value in $map destructures each pair. The interpolation #{$key} puts the key in the class name. Six entries times four rules gives 24 classes from eight lines.

To avoid listing every property by hand, nest a second loop over a map of abbreviations to properties and a third over sides:

SCSS
$properties: (m: margin, p: padding);
$sides: (t: top, r: right, b: bottom, l: left);

@each $abbr, $prop in $properties {
  @each $key, $value in $spacing {
    .#{$abbr}-#{$key} { #{$prop}: $value; }

    @each $side-abbr, $side in $sides {
      .#{$abbr}#{$side-abbr}-#{$key} { #{$prop}-#{$side}: $value; }
    }
  }
}

Property names can be interpolated too: #{$prop}-#{$side} becomes margin-top.

Spacing utilities

Add a new size (4: 2rem) to the map and use p-4 in the demo. The generator needed no other change.

Color helpers from a map

SCSS
$theme-colors: (primary: #4f46e5, success: #15803d, danger: #b91c1c);

@each $name, $color in $theme-colors {
  .text-#{$name} { color: $color; }
  .bg-#{$name}   { background-color: $color; }
  .border-#{$name} { border-color: $color; }
}

Combine with Sass color functions to generate shades:

SCSS
@use "sass:color";

@each $name, $color in $theme-colors {
  @each $step in (10, 20, 30) {
    .bg-#{$name}-light-#{$step} { background-color: color.mix(white, $color, $step * 1%); }
  }
}

$step * 1% turns the plain number into a percentage for color.mix.

A numeric grid with @for

@for $i from 1 through 12 runs the body for 1, 2, ..., 12 (inclusive). With to the end value is excluded.

SCSS
@use "sass:math";

$columns: 12;

.row { display: flex; flex-wrap: wrap; }

@for $i from 1 through $columns {
  .col-#{$i} { flex: 0 0 math.percentage(math.div($i, $columns)); max-width: math.percentage(math.div($i, $columns)); }
}

.col-6 becomes 50%, .col-4 33.3333333333%.

A 12-column grid

Responsive variants

The same utilities at each breakpoint are generated by wrapping the loop in a mixin and calling it once per breakpoint with a class-name infix:

SCSS
$breakpoints: (sm: 40rem, md: 48rem, lg: 64rem);

@mixin spacing-utilities($infix: "") {
  @each $key, $value in $spacing {
    .p#{$infix}-#{$key} { padding: $value; }
    .m#{$infix}-#{$key} { margin: $value; }
  }
}

@include spacing-utilities;                    // .p-1, .m-1 ...

@each $bp, $width in $breakpoints {
  @media (min-width: $width) {
    @include spacing-utilities("-#{$bp}");     // .p-md-1, .m-md-1 ...
  }
}

Putting the infix before the value (.p-md-3) avoids the colon in names such as md:p-3, which needs escaping in CSS (.md\:p-3). If you want the colon style, escape it in the selector: .md\:p-#{$key}.

Responsive spacing utilities

Look at the compiled CSS: the md utilities are inside a media query and come after the base ones, so they win when both apply (same specificity, later source order).

A utility API map

Real frameworks describe every utility family in one data structure: property, class prefix, values, whether it is responsive. One loop reads it:

SCSS
$utilities: (
  "opacity": (property: opacity, class: o, values: (0: 0, 50: 0.5, 100: 1)),
  "text-align": (property: text-align, class: text, values: (left: left, center: center, right: right)),
  "display": (property: display, class: d, values: (none: none, block: block, flex: flex)),
);

@each $name, $config in $utilities {
  @each $key, $value in map.get($config, values) {
    .#{map.get($config, class)}-#{$key} {
      #{map.get($config, property)}: $value;
    }
  }
}

Adding a utility means adding data, not loops. This is the design behind Bootstrap's utilities API.

Keep the output under control

Generators are powerful and dangerous: multiplying sizes, properties, breakpoints and states explodes quickly. 8 spacing values ร— 2 properties ร— 5 sides ร— 4 breakpoints is already 320 rules.

  • Generate only what you use. Choose a short scale and a few breakpoints.
  • Skip pseudo-class variants (hover, focus) unless you really need them.
  • Measure. Compare compiled sizes before and after (minified and gzipped).
  • Purge unused classes in production with a tool that scans your markup, covered in performance and output size.
  • Prefer components for repeated combinations. If every button has p-3 bg-primary text-white rounded, that is a component, not four utilities.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @for $i from 1 through 3 iterate over?

    through includes the end value; to would exclude it.
  2. 2. How do you build the class name .mt-2 from $key: 2?

    Selectors need interpolation to include variable values.
  3. 3. How can a loop output a property name such as margin-top?

    Property names can be interpolated just like selectors.
  4. 4. Why call the spacing mixin inside an @media rule with an infix?

    The infix keeps class names unique and the media query limits when they apply.
  5. 5. What is a good way to keep generated CSS from growing too large?

    Output multiplies quickly, so trim the data and purge unused classes.

Summary

  • Describe utilities as maps and generate classes with @each and @for; interpolate class and property names.
  • Use a mixin with an infix argument to repeat families inside each breakpoint.
  • A utility API map lets one loop produce every family.
  • Control output size: short scales, few variants, measurement and purging.
  • Turn repeated utility combinations into components.

Next: Sass CLI, Watch Mode and Source Maps