# Utility

A utility, in the context of CUBE CSS, is a CSS class that does one job and does that one job well.

This CSS class—more often than not—will have only one CSS property defined, such as a background colour. It might also have a few CSS properties defined, in a concise group, like this example of a wrapper utility:

.wrapper {
  margin-inline: auto;
  padding-inline: 1rem;
  max-width: 60rem;
}

This handy utility provides a consistent max width, padded container that sits in the middle of the viewport when the viewport is greater than 60rem wide.

One job: done well.

# Token-based CSS

CUBE CSS works exceedingly well in design systems because the utility layer works hand-in-hand with design tokens (opens new window).

Design tokens—more often than not—will be defined away from your CSS codebase, so to use them with the CUBE CSS methodology, it is recommended that you generate utility classes.

In this example, let’s say you have a set of design tokens defined in a JSON file like this:

{
  "colors": {
    "primary": "#ff00ff",
    "secondary": "#ffbf81",
    "base": "#252525"
  }
}

You could then—using a tool—generate utility classes that represent each token in a CSS property. For example, here’s some resulting color and background utility classes:

.bg-primary {
  background: #ff00ff;
}
.bg-secondary {
  background: #ffbf81;
}
.color-primary {
  color: #ff00ff;
}
.color-secondary {
  color: #ffbf81;
}

With those classes generated, we would apply them to HTML, like so:

<article class="bg-primary color-base"></article>

Applying our design tokens like this allows us to define things once and apply them everywhere—maintaining the premise that design tokens are a single source of truth.

# What should utilities do?

  1. Apply a single CSS property, or a concise group of related properties to create re-usable helpers
  2. Extend design tokens to maintain a single source of truth
  3. Abstract repeatability away from the CSS and apply it in the HTML instead

# What shouldn’t utilities do?

  1. Define a large group of unrelated CSS properties. For example, a utility that defined color, font-size and padding would make more sense to be a block.
  2. Be used as a specificity hack. For example, setting all properties with !important will undoubtedly cause problems in the long-run.