Generating Utility Classes from Design Tokens using Style Dictionary 🔗 **Source:** [Generating Utility Classes from Design Tokens using Style Dictionary](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter) > [!note]+ Document Notes > tags: [design-tokens, css, style-dictionary] > author: Always Twisted > source: alwaystwisted.com > reference: [https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter] > date created: 2025-11-26 00:00 > > # 🏷️ Title: Generating Utility Classes from Design Tokens using Style Dictionary > <!-- deep-read:sections start --> ## 🧭 Table of Contents - [📝 Summary](#-summary) - [📖 Main Content](#-main-content) - [🗒️ Notes](#️-notes) - [📚 References](#-references) - [🗣️ Paraphrase](#️-paraphrase) - [📰 Newsletter](#-newsletter) - [✅ Action Items](#-action-items) - [🧪 Hypotheses](#-hypotheses) - [📊 Methodology](#-methodology) - [❓ Questions](#-questions) - [🔮 Future Research](#-future-research) - [💡 Implications](#-implications) - [🧠 Learning Styles Assessment](#-learning-styles-assessment) - [📊 Accessibility Assessment](#-accessibility-assessment) - [🌍 DEIB Assessment](#-deib-assessment) - [✅ Logical Validity](#-logical-validity) - [🛡️ DARVO Analysis](#-darvo-analysis) - [🎯 Conclusion](#-conclusion) ### 🔗 References - Include links cited in or relevant to the article. ## 📝 Summary - What happened: The author shows how to generate CSS utility classes (spacing, color, typography) directly from design tokens using Style Dictionary, including custom formats and a shared utility config file. - Why it matters: Keeps one-off designs aligned with the design system, avoids hard-coded values, and automates synchronization between tokens and CSS. - Key stakeholders: Design system teams, frontend engineers, design ops, and product teams needing fast iteration without design drift. - Risks and tradeoffs: More build complexity, multiple files to maintain, repeated logic per utility type, and potential cognitive overhead for newcomers. - Bottom line: Centralize design decisions as tokens, generate utilities via Style Dictionary formats, and separate configuration from generation logic for maintainable, reusable workflows. ## 📖 Main Content - The article argues that utility classes are a middle ground between rigid components and bespoke CSS. When generated from tokens, utilities ensure even “snowflake” UI stays “of the design system,” not random. - Token examples cover colors, spacing, and typography (font size, weight, family), structured to reflect how those values evolve at different rates. - Style Dictionary’s `registerFormat` API is used to define custom CSS output formats for: - Spacing utilities (`.padding--100`, `.margin-top--400`, etc.) - Color utilities (`.text-red--500`, `.bg-blue--400`, `.border-green--300`) - Typography utilities (`.font-size--300`, `.font-weight--700`, `.font-family--code`) - The core mechanism: - Style Dictionary loads tokens. - Custom formats iterate `dictionary.allTokens`, filter by token path (e.g., `token.path[0] === 'color'`), and write CSS rules using `token.$value`. - Returned strings become CSS files such as `utilities-color.css`, `utilities-spacing.css`, etc. - Two configuration styles are compared: - All-in-one `build.js`: utility definitions (prefix/property pairs) live inside each format function—simple and visible but hard to reuse and scale. - Extracted `config/utilities.js`: utility definitions live in a shared config object (`utilityConfig.spacing`, `.color`, `.fontSize`, `.fontWeight`, `.fontFamily`), imported into `build.js`. This cleans up build logic, eases cross-project reuse, and lets non-devs edit the config without touching build code. - The article then extends the pattern to semantic color tokens (e.g., `color.semantic.primary` referencing raw `color.blue.500`), generating more expressive utilities like `.text--primary` alongside low-level `.text-red--500`. - The conclusion: automated utility generation keeps CSS in sync with tokens; changing a token updates utilities, constraining teams to system values while preserving speed and flexibility. ### 🗒️ Notes - Utility classes are presented as a mechanism to “offer a middle ground between rigid components and completely custom CSS,” especially for “one-off designs” that still need to respect system values. - Tokens are organized into small, purpose-focused files (e.g., separate typography files for size, weight, family) to reflect different change cadences and ease navigation. - Style Dictionary concepts: - `registerFormat({ name, format })` defines a named output format. - `dictionary.allTokens` exposes processed tokens, each with: - `path` (hierarchical location, e.g., `['color','red','500']`) - `$value` (resolved output like `#f00` or `0.75rem`). - Utility generation pattern: - Define a list of utilities, each with `prefix` and CSS `property` (e.g., `{ prefix: 'padding-top', property: 'padding-top' }`). - For each utility, filter tokens by top-level category (`spacing`, `color`, `font`) and construct class names from token paths. - Output CSS strings like: - `.padding--100 { padding: 0.25rem; }` - `.text-red--500 { color: #f00; }` - `.font-size--300 { font-size: 1rem; }` - Config extraction: - `config/utilities.js` holds arrays like: - `spacing`: padding/margin variants. - `color`: text/background/border color mappings. - `fontSize`, `fontWeight`, `fontFamily`: typography mappings. - `build.js` imports `utilityConfig` and loops over each category to generate CSS; the logic stays the same, only the source of utility definitions changes. - Tradeoffs: - Single-file approach: fewer files, easy to understand for small setups; but mixes configuration with generation logic and becomes unwieldy as utilities grow. - Separated config: adds another file and keeps per-format registration boilerplate, but significantly improves maintainability, clarity, and reuse. - Semantic utilities: - Introduces semantic tokens (e.g., `color.semantic.primary`) referencing base palette tokens. - Another custom format filters tokens whose path includes `['color','semantic']` and generates semantic classes such as `.text--primary`. - This provides a layered utility system: low-level palette utilities and higher-level semantic utilities indicating design intent. - Overall, the workflow “bridges the gap” between the design system and the fast-paced realities of UI building, enforcing token usage while enabling quick composition with classes. ## 📚 References - [Article: Generating Utility Classes from Design Tokens using Style Dictionary](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter) - [Style Dictionary (Amazon)](https://amzn.github.io/style-dictionary/#/) - [Design Tokens Community Group](https://design-tokens.github.io/community-group/format/) ## 🗣️ Paraphrase - Paragraph A paraphrase: The author explains how to generate CSS utility classes from design tokens using Style Dictionary, covering spacing, colors, and typography with custom formats and a shared configuration file to keep code maintainable. - Paragraph B paraphrase: They show that by automating utility generation from tokens—including semantic tokens—teams can rapidly build unique interfaces that still adhere to design system values, with changes to tokens automatically reflected in the resulting CSS. ## 📰 Newsletter A fresh deep-dive into design tokens and CSS utilities has big implications for modern WordPress theming. In “Generating Utility Classes from Design Tokens using Style Dictionary,” Always Twisted walks through turning tokens into reusable spacing, color, and typography utilities via custom Style Dictionary formats and a shared config file. If you’re working with `theme.json`, block themes, or design systems around Gutenberg, this pattern can inspire how you map tokens to utility-like classes or global styles, while keeping everything in sync with a single source of truth. Resources worth exploring: - Style Dictionary for token-to-CSS pipelines: https://amzn.github.io/style-dictionary/#/ - WordPress `theme.json` reference for token-like settings: https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/ - Design Tokens Community Group format: https://design-tokens.github.io/community-group/format/ Expect faster iteration, fewer hard-coded styles, and more consistent experiences across blocks, patterns, and full-site editing. ## ✅ Action Items #### DevRel - Document a minimal example repo showing Style Dictionary generating utilities from tokens for a component library. - Create a short workshop or screencast: “From tokens to utilities with Style Dictionary.” - Publish quickstart snippets for integrating Style Dictionary into existing CSS/SCSS or PostCSS-based workflows. - Collect developer feedback on utility naming schemes (numeric vs semantic) and refine guidance. #### OSPO - Recommend a standard token format and Style Dictionary configuration for internal design systems. - Add token and utility generation checks to CI to ensure license-compliant dependencies and consistent outputs. - Define a governance doc on how semantic tokens (e.g., `primary`) are named and evolved. #### Community - Host a small clinic for maintainers on moving from ad-hoc CSS to token-driven utilities. - Encourage contributors to propose new utilities by editing config files rather than scattered CSS. #### WordPress - Core: Explore how token-based utility patterns could inform future CSS organization or shared styles in core. - Core Performance: Benchmark utility-based CSS bundles vs ad-hoc styles for theme/page performance. - Core AI: Prototype tools that infer design tokens from existing themes and suggest utility mappings. - Core Program Team: Align design system, editor, and theme contributors on shared token naming guidelines. - Playground: Provide a sandbox showing Style Dictionary + a block theme using generated utilities. - Community: Add a design-tokens-and-utilities track to WordCamps or meetups. - Training: Create lesson plans on design tokens and utility classes for theme and plugin builders. - Marketing: Highlight case studies where token workflows simplify enterprise theming. - Support: Add KB entries explaining pros/cons of token-based utilities for theme customization. - Design: Integrate token structures and utility generation considerations into UX design processes. - Documentation: Add “examples-first” docs mapping JSON tokens to CSS and block styles. - Photos/TV/Polyglots/etc.: Not directly impacted beyond using shared tokens for branding where relevant. - Accessibility: Ensure token usage supports accessible color and spacing defaults by design. - Meta: Consider `.org` tooling that reads tokens from themes and visualizes generated styles. - CLI: Explore commands to scaffold basic token files and Style Dictionary config. - Hosting/Tide/Openverse/Themes/Plugins: Encourage token-friendly architectures where appropriate, but not primary here. #### The WPOCC - Run documentation sprints focusing on tokenization of existing community theme patterns. - Offer microgrants for maintainers experimenting with token-based utility pipelines in WordPress ecosystems. ### FAIR - Promote token storage and build pipelines that can run locally and do not lock users into proprietary services. - Publish transparent governance around funding and maintaining shared token/utility tooling. - Provide reusable charters and scorecards for evaluating design system/tooling independence. ## 🧪 Hypotheses - H1: Generating CSS utilities from tokens reduces the number of hard-coded styles in a project. - H2: Separating utility configuration into its own file improves maintainability and reuse across projects. - H3: Combining numeric and semantic utilities yields faster adoption and fewer naming conflicts than either alone. - H4: Teams using Style Dictionary for utilities will keep design decisions more consistent across products. ### 📊 Methodology - For H1: Analyze CSS codebases before and after adopting token-based utilities; count hard-coded values vs token-derived declarations. - For H2: Compare change frequency and defect rates between projects using inlined vs extracted utility configs. - For H3: Conduct usability tests and naming surveys with developers/designer pairs working with numeric-only, semantic-only, and hybrid schemes. - For H4: Survey product teams on perceived consistency and run UI audits for token adherence across multiple apps. ### ❓ Questions - How large can a utility set grow before it becomes unwieldy, even when generated from tokens? - What naming conventions best balance readability, backward compatibility, and design intent? - How should semantic tokens be governed to avoid “primary-2-3-4” sprawl? - Can WordPress `theme.json` act as a source of tokens for a cross-platform Style Dictionary pipeline? ### 🔮 Future Research - Explore bidirectional sync: updating utilities or themes feeding back into token proposals. - Investigate how design tools (Figma, etc.) can export directly into the token format used by Style Dictionary. - Study the impact of utility-based token usage on onboarding time for new developers. - Examine patterns for multi-brand token hierarchies and their generated utilities. ### 💡 Implications - Practice: Shifts styling from scattered CSS rules to centrally governed tokens and generated utilities. - Policy: Encourages teams to codify design decisions (colors, spacing, typography) into shared standards. - Security: Indirect; more predictable CSS may simplify review, but no direct security change. - Education: Requires training designers and developers in token thinking and build pipelines. - Funding: Design system tooling (including Style Dictionary integrations) becomes a clearer investment target. ### 🧠 Learning Styles Assessment - Reading level estimate: Roughly upper-intermediate technical (Flesch–Kincaid ~10–12), due to jargon (tokens, utilities, config) and code-heavy explanations. #### 👀 Visual learners - Present: Conceptual explanation of token hierarchies; implied code structure. - Improve: Add diagrams of token trees, build pipeline flow, and before/after CSS architecture. #### 🔊 Aural learners - Present: None. - Improve: Provide a short audio walkthrough or screencast describing the pipeline and key decisions. #### 🗣️ Verbal learners - Present: Clear term definitions (tokens, paths, values) and stepwise narrative of config evolution. - Improve: More analogies (e.g., tokens as “ingredients,” utilities as “recipes”). #### 🧩 Kinesthetic learners - Present: Code samples that can be copied and run. - Improve: Guided “lab” instructions with explicit steps and checkpoints. #### 🧠 Logical learners - Present: Sequential explanation of formats, config extraction, and tradeoffs. - Improve: Add tables comparing approaches and explicit decision trees for when to adopt each. #### 🧑‍🤝‍🧑 Social learners - Present: None explicit. - Improve: Suggest pair-programming exercises and review checklists for teams adopting tokens. #### 🧘‍♀️ Solitary learners - Present: Dense article suitable for solo study and experimentation. - Improve: Self-check questions and reflection prompts at the end. #### 🌿 Naturalistic learners - Present: None. - Improve: Analogies to ecosystem balance (tokens as shared environment variables across different species/components). ### 📊 Accessibility Assessment #### Screen reader semantics - Present: Likely standard headings and code blocks; specifics not detailed. - Improve: Ensure semantic headings, code labels, and descriptive text around examples. #### Keyboard navigation - Present: Not discussed. - Improve: Standard web best practices; ensure code examples are reachable and selectable. #### Contrast and readability - Present: Not discussed. - Improve: Ensure examples and UI screenshots (if any) meet contrast guidelines. #### Text resizing and reflow - Present: Likely responsive text, but not detailed. - Improve: Verify article layout at high zoom and with reduced-motion preferences. #### Media and captions - Present: Primarily text and code. - Improve: If videos are added, include captions and transcripts. #### Forms and interactions - Present: N/A (article). - Improve: N/A. #### Standards reference - Gaps likely around explicit WCAG 2.2 AA checks for contrast, reflow, and media alternatives. ### 🌍 DEIB Assessment #### Cultural breadth - Present: Neutral, technical content with no regional focus. - Improve: Include examples from varied platforms and contexts. #### Inclusive language - Present: Generally neutral and inclusive. - Improve: Add more explanations for jargon and avoid assuming prior Style Dictionary experience. #### Neurodiversity support - Present: Structured sections and repeated patterns (e.g., similar format for each utility). - Improve: More chunked summaries, bullet lists, and clear visual hierarchies. #### Representation - Present: Not applicable; no people depicted. - Improve: If adding illustrations, ensure diverse representation and alt text. #### Psychological safety - Present: Respectful, non-judgmental tone. - Improve: Encourage experimentation and note that different teams can adapt patterns. ### ✅ Logical Validity #### Strong reasoning - The comparison between single-file and extracted config approaches is a clear inductive argument: it lists concrete benefits and drawbacks, then justifies why separation usually wins as complexity grows. - The claim that generating utilities from tokens keeps CSS in sync is causally grounded: token changes flow through build steps to regenerated CSS. #### Fallacies - None apparent; claims are modest and grounded in practical experience rather than universal generalizations. #### Tone of voice - Tone is pragmatic, instructional, and slightly conversational. It balances concrete steps with rationale, emphasizing maintainability and real-world constraints. ### 🛡️ DARVO Analysis - Deny: No denial or minimization of responsibility or harm; article is purely technical. - Attack: No attacks on individuals or groups. - Reverse victim/offender: Not present; there is no interpersonal conflict described. ## 🎯 Conclusion Generating CSS utility classes from design tokens with Style Dictionary offers a scalable way to keep “snowflake” UI consistent with your design system. By structuring tokens well, defining custom formats, and extracting utility configuration into its own module, teams gain faster iteration, better reuse, and more maintainable styling pipelines, all while keeping CSS aligned with a single source of design truth. ## 🧱 Refactor Appendix (append after 🎯 Conclusion) ### 📚 Literature Split Pad - Purpose: Stage Konik CEE units that become per-source Literature notes. - Split level: **H3**. - Include verbatim quotes under 25 words and a [view highlight] link. ### [H1] 5–10-word present-tense claim > [!quote] [Generating Utility Classes from Design Tokens using Style Dictionary](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter) by [[Always Twisted]] via [[alwaystwisted.com]]. Published 2025-11-21. > “By automating this process with Style Dictionary, we can ensure that utility classes should stay in sync with our tokens.” Two lines: context and use. Cite data if relevant. [view highlight](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter#H1) #xref #articleseed ID:rw_[MISSING] ### [H2] 5–10-word present-tense claim > [!quote] [Generating Utility Classes from Design Tokens using Style Dictionary](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter) > “Utility classes can really help offer a middle ground between rigid components and completely custom CSS.” Two lines: context and use. [view highlight](https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter#H2) #xref ID:rw_[MISSING] --- ### 🔖 Atomic Split Pad (Zettel Candidates) - Purpose: Promote reusable claims into Atomic notes. - Split level: **H4**. - Each item: one idea, present tense, specific, testable. #### [Z1] Token-based utilities keep CSS consistent - Scope/condition in one line. - Pointer to page/time or dataset. - Links: [[Design-Tokens]] [[Utility-Classes]] #### [Z2] Extracted configs improve utility maintainability - Scope/condition in one line. - Pointer to page/time or dataset. - Links: [[Build-Architecture]] [[Style-Dictionary]] --- ### ✏️ Fleeting Queue (Extract by Selection) - Purpose: Capture quick actions or sparks for Fleeting notes. - Extraction: **Select one line** → “Refactor: Extract selection to new note (content only).” - Keep each line short and self-contained. - [F1] Try extracted `utilityConfig` pattern in current design system repo/{https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter} #fleeting #inbox - [F2] Prototype semantic color utilities (`.text--primary`) alongside numeric ones/{https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter} #fleeting #inbox - [F3] Map WordPress `theme.json` settings into Style Dictionary tokens/{https://www.alwaystwisted.com/articles/a-design-tokens-workflow-part-13?utm_source=the-index&utm_medium=newsletter} #fleeting #inbox --- <!-- deep-read:sections end -->