Skip to content

How to Use USWDS Tokens

Chris Wachtman edited this page Mar 18, 2024 · 20 revisions

The US Web Design System provides a comprehensive selection of Design Tokens and 4 ways to access the values that they represent.

The 4 Ways to Use Tokens

Utility Class

Quick styling of HTML without adding new CSS.

<div class="border-top-2px border-red bg-white text-base-darkest margin-bottom-3 desktop:padding-x-4">
  Example
</div>

Theme Variable

Modify the USWDS defaults.

$theme-focus-color: 'cyan-50v';

List of available USWDS Theme Variables

Utility Mixin

Add several USWDS styles within a class, so HTML does not need so many utility classes. The HTML below gets the same styles as the Utility Class example.

.example {
  @include u-border-top(2px, 'red');
  @include u-bg('white');
  @include u-text('base-darkest');
  @include u-margin-bottom(3);
  @include at-media("desktop") {
    @include u-padding-x(4);
  }
}
<div class="example">
  Example
</div>

Token Function

Use tokens within styles that USWDS does not have Mixins for. This example creates a gradient using USWDS color() values.

.example {
  background: linear-gradient(90deg, color('cyan-30v') 0%, color('magenta-20') 100%);
}

Each category of tokens uses a different function for obtaining values. There are 4 functions (color, units, size, and family) referenced here.

Comparison Chart

Option Utility Classes Theme Variables Utility Mixins Token Functions
Where to use HTML _uswds-theme.scss SCSS SCSS
What it does Apply styles Change USWDS Copy styles Copy token values
Example .bg-white $theme-color-info: "red” u-bg('white') color('red')
Best for Small style tweaks Site-wide changes Many styles with 1 class When there’s no mixin

Note: I believe we need to add @use "uswds-core" as *; at the top of our scss files to use USWDS Mixins and Functions.

Create Our Own Tokens

We can create our own tokens in _uswds-theme.scss like this:

$color-manual-values: (
  'coffee': #c0ffee,
)

USWDS will produce all the utility classes, mixins and functions for us.

<div class="bg-coffee">
  Utility Class Example
</div>
.mixin-example {
  @include u-bg('coffee');
}
.function-example {
  background: color('coffee');
}