JavaScript and React course ยท Module 14: Advanced Styling

Design Tokens and Systematic CSS - Cosmic Design Code

5 min read ยท
In this lesson10

Pilot, imagine that every ship in the galactic fleet uses exactly the same status colors, the same spacing between panels, and the same typography on monitors. This is no coincidence -- it's a design system. In the frontend world, the equivalent is design tokens -- a central source of truth for all visual values in the application.

What are Design Tokens?

Design tokens are named values representing design decisions: colors, spacing, font sizes, shadows, border radii. Instead of scattering magic numbers throughout the code, you define them in one place:

// tokens.js -- central source of truth
const tokens = {
  colors: {
    primary: '#7c4dff',
    primaryLight: '#b388ff',
    primaryDark: '#651fff',
    success: '#00e676',
    warning: '#ffa726',
    danger: '#f44336',
    bgDark: '#0a0a2e',
    bgSurface: '#1a1a4e',
    textPrimary: '#e0e0e0',
    textMuted: '#9e9e9e',
    border: '#3949ab',
  },
  spacing: {
    xs: '4px',
    sm: '8px',
    md: '16px',
    lg: '24px',
    xl: '32px',
    xxl: '48px',
  },
  fontSize: {
    xs: '12px',
    sm: '14px',
    md: '16px',
    lg: '20px',
    xl: '28px',
    xxl: '36px',
  },
  borderRadius: {
    sm: '4px',
    md: '8px',
    lg: '12px',
    xl: '20px',
    full: '9999px',
  },
  shadows: {
    sm: '0 2px 4px rgba(0,0,0,0.1)',
    md: '0 4px 12px rgba(0,0,0,0.2)',
    lg: '0 8px 24px rgba(0,0,0,0.3)',
    glow: '0 0 20px rgba(124,77,255,0.3)',
  },
};

Using tokens in components

Once you have tokens defined, you use them instead of direct values:

import { tokens } from './tokens';

// In inline styles
function Card({ children }) {
  return (
    <div style={{
      background: tokens.colors.bgSurface,
      padding: tokens.spacing.lg,
      borderRadius: tokens.borderRadius.lg,
      border: `1px solid ${tokens.colors.border}`,
    }}>
      {children}
    </div>
  );
}
// In styled-components
const Card = styled.div`
  background: ${tokens.colors.bgSurface};
  padding: ${tokens.spacing.lg};
  border-radius: ${tokens.borderRadius.lg};
  border: 1px solid ${tokens.colors.border};
`;

Tokens as CSS Variables

The best approach is to combine JavaScript tokens with CSS Variables -- you define tokens in JS (easy to manage) and pass them to CSS as variables (efficient rendering):

function applyTokens(tokens) {
  const vars = {};
  vars['--color-primary'] = tokens.colors.primary;
  vars['--color-bg'] = tokens.colors.bgDark;
  vars['--color-surface'] = tokens.colors.bgSurface;
  vars['--color-text'] = tokens.colors.textPrimary;
  vars['--spacing-md'] = tokens.spacing.md;
  vars['--spacing-lg'] = tokens.spacing.lg;
  vars['--radius-lg'] = tokens.borderRadius.lg;
  return vars;
}

function App() {
  return (
    <div style={applyTokens(tokens)} className="app">
      {/* CSS uses var(--color-primary) etc. */}
    </div>
  );
}

Consistent color system

A good color system has structure:

const colorSystem = {
  // Base colors
  blue: { 50: '#e3f2fd', 100: '#bbdefb', 500: '#2196f3', 900: '#0d47a1' },
  purple: { 50: '#f3e5f5', 100: '#e1bee7', 500: '#9c27b0', 900: '#4a148c' },

  // Semantic colors (used in code)
  primary: 'var(--blue-500)',
  success: 'var(--green-500)',
  warning: 'var(--orange-500)',
  danger: 'var(--red-500)',

  // Surface colors
  background: '#0a0a2e',
  surface: '#1a1a4e',
  surfaceHover: '#2a2a5e',
};

Semantic colors (primary, success, danger) are separated from base colors (blue-500, red-400). This way, changing the theme is just a mapping change, not searching through the entire codebase.

Spacing system

Spacing based on a scale -- each next value is a multiple of the base:

// 4px scale (Tailwind-style)
const spacing = {
  0: '0px',
  1: '4px',
  2: '8px',
  3: '12px',
  4: '16px',
  5: '20px',
  6: '24px',
  8: '32px',
  10: '40px',
  12: '48px',
  16: '64px',
};

Using a scale instead of arbitrary values guarantees visual consistency -- elements on the screen are evenly spaced, giving a professional look.

Typography as a system

const typography = {
  fontFamily: {
    sans: "'Inter', 'Segoe UI', sans-serif",
    mono: "'Fira Code', monospace",
  },
  fontSize: {
    xs: ['12px', { lineHeight: '16px' }],
    sm: ['14px', { lineHeight: '20px' }],
    base: ['16px', { lineHeight: '24px' }],
    lg: ['20px', { lineHeight: '28px' }],
    xl: ['28px', { lineHeight: '36px' }],
    '2xl': ['36px', { lineHeight: '44px' }],
  },
  fontWeight: {
    normal: 400,
    medium: 500,
    semibold: 600,
    bold: 700,
  },
};

Each font size has an assigned line height -- this eliminates typographic chaos.

Token Composition -- composing tokens

An advanced pattern is token composition -- creating more specific tokens from base ones:

// Base tokens (primitive)
const primitives = {
  blue500: '#7c4dff',
  blue300: '#b388ff',
  green500: '#00e676',
  red500: '#f44336',
  gray900: '#0a0a2e',
  gray800: '#1a1a4e',
  gray100: '#e0e0e0',
  gray400: '#9e9e9e',
};

// Semantic tokens (composed from base)
const semantic = {
  colorPrimary: primitives.blue500,
  colorPrimaryLight: primitives.blue300,
  colorSuccess: primitives.green500,
  colorDanger: primitives.red500,
  colorBackground: primitives.gray900,
  colorSurface: primitives.gray800,
  colorText: primitives.gray100,
  colorTextMuted: primitives.gray400,
};

// Component tokens (composed from semantic)
const components = {
  buttonPrimaryBg: semantic.colorPrimary,
  buttonPrimaryText: '#ffffff',
  buttonDangerBg: semantic.colorDanger,
  cardBg: semantic.colorSurface,
  cardBorder: primitives.blue500 + '40',
};

Three layers: base (values) -> semantic (meaning) -> component (usage). Changing a single base token cascades updates everywhere.

Style Dictionary -- automating tokens

In large projects, tokens are stored in JSON format and automatically generated for different platforms using the Style Dictionary tool:

{
  "color": {
    "primary": { "value": "#7c4dff" },
    "success": { "value": "#00e676" },
    "background": { "value": "#0a0a2e" }
  },
  "spacing": {
    "sm": { "value": "8px" },
    "md": { "value": "16px" },
    "lg": { "value": "24px" }
  }
}

Style Dictionary generates from this:

  • CSS Variables -- for web applications
  • JavaScript/TypeScript -- for React
  • Swift/Kotlin -- for mobile applications

One source of truth, multiple output formats.

Automating consistency

Creating a TokenPreview component helps control the entire system:

function TokenPreview({ tokens }) {
  return (
    <div>
      <h2>Colors</h2>
      {Object.entries(tokens.colors).map(([name, value]) => (
        <div key={name} style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <div style={{ width: 40, height: 40, background: value, borderRadius: 8 }} />
          <span>{name}: {value}</span>
        </div>
      ))}

      <h2>Spacing</h2>
      {Object.entries(tokens.spacing).map(([name, value]) => (
        <div key={name} style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <div style={{ width: value, height: 16, background: '#7c4dff' }} />
          <span>{name}: {value}</span>
        </div>
      ))}
    </div>
  );
}

When to use design tokens?

  • Any project larger than a landing page -- tokens save time in the long run
  • Team collaboration -- every developer uses the same values
  • Multiple themes -- changing one object changes the entire appearance
  • Cross-platform consistency -- Style Dictionary generates tokens for React, React Native, iOS, Android
  • Token composition -- three layers (base -> semantic -> component) give full control
Code for this lesson: App.jsx
import React, { useState } from 'react';
import './styles.css';

// Design tokens -- single source of truth
const tokens = {
  colors: {
    primary: '#7c4dff', primaryLight: '#b388ff', primaryDark: '#651fff',
    success: '#00e676', warning: '#ffa726', danger: '#f44336',
    bgDark: '#0a0a2e', bgSurface: '#1a1a4e',
    textPrimary: '#e0e0e0', textMuted: '#9e9e9e', border: '#3949ab',
  },
  spacing: { xs: '4px', sm: '8px', md: '16px', lg: '24px', xl: '32px' },
  fontSize: { xs: '12px', sm: '14px', md: '16px', lg: '20px', xl: '28px' },
  borderRadius: { sm: '4px', md: '8px', lg: '12px', full: '9999px' },
};

// Converting tokens to CSS Variables
function tokensToVars(t) {
  return {
    '--color-primary': t.colors.primary,
    '--color-primary-light': t.colors.primaryLight,
    '--color-success': t.colors.success,
    '--color-warning': t.colors.warning,
    '--color-danger': t.colors.danger,
    '--color-bg': t.colors.bgDark,
    '--color-surface': t.colors.bgSurface,
    '--color-text': t.colors.textPrimary,
    '--color-text-muted': t.colors.textMuted,
    '--color-border': t.colors.border,
    '--spacing-sm': t.spacing.sm,
    '--spacing-md': t.spacing.md,
    '--spacing-lg': t.spacing.lg,
    '--radius-lg': t.borderRadius.lg,
  };
}

// Color preview
function ColorSwatch({ name, value }) {
  return (
    <div className="swatch">
      <div className="swatch-color" style={{ background: value }} />
      <div className="swatch-info">
        <span className="swatch-name">{name}</span>
        <span className="swatch-value">{value}</span>
      </div>
    </div>
  );
}

// Spacing preview
function SpacingBar({ name, value }) {
  return (
    <div className="spacing-row">
      <span className="spacing-name">{name}</span>
      <div className="spacing-bar" style={{ width: value, background: 'var(--color-primary)' }} />
      <span className="spacing-value">{value}</span>
    </div>
  );
}

// Example of using tokens in a component
function TokenCard({ title, children }) {
  return (
    <div className="token-card">
      <h3 className="token-card-title">{title}</h3>
      {children}
    </div>
  );
}

function TokenButton({ variant, children }) {
  return (
    <button className={`token-btn token-btn-${variant}`}>{children}</button>
  );
}

export default function App() {
  return (
    <div style={tokensToVars(tokens)} className="app">
      <h1 className="heading">Design Tokens</h1>
      <p className="subtitle">Single source of truth -- all values in one place</p>

      <TokenCard title="Colors">
        <div className="swatch-grid">
          {Object.entries(tokens.colors).map(([name, value]) => (
            <ColorSwatch key={name} name={name} value={value} />
          ))}
        </div>
      </TokenCard>

      <TokenCard title="Spacing">
        {Object.entries(tokens.spacing).map(([name, value]) => (
          <SpacingBar key={name} name={name} value={value} />
        ))}
      </TokenCard>

      <TokenCard title="Components using tokens">
        <div className="component-demo">
          <TokenButton variant="primary">Primary</TokenButton>
          <TokenButton variant="success">Success</TokenButton>
          <TokenButton variant="danger">Danger</TokenButton>
          <TokenButton variant="outline">Outline</TokenButton>
        </div>
        <p className="demo-note">
          Each button uses var(--color-...) from the tokens.
          Changing a token changes all components at once!
        </p>
      </TokenCard>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What are design tokens in the context of frontend development?

  2. 2. Why is it worth separating semantic colors (primary, danger) from base colors (blue-500, red-400) in a design tokens system?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the syntax for using a color token in CSS with a CSS Variable:

  • Horizontal ordering

    Arrange the syntax for defining a spacing token in a JavaScript object:

  • Click in order

    Arrange the steps for converting a JavaScript token to a CSS Variable in React:

  • Vertical ordering

    Arrange the design tokens system layers from the most basic to the most specific:

  • Vertical ordering

    Arrange the steps for implementing design tokens in a new React project:

  • Code editor

    Create a design tokens system and use it in a component

  • Vertical ordering

    Arrange the font size tokens from smallest to largest:

  • Code editor

    Create a visual preview of color tokens

  1. QuestionWhat Are Design Tokens
  2. Put in orderUsing a Token in CSS
  3. QuestionSemantic vs Base Colors
  4. Put in orderSpacing Token Definition
  5. Click in orderToken to CSS Variable
  6. Put in orderDesign Tokens System Layers
  7. Put in orderImplementing Design Tokens in a Project
  8. QuestionBenefits of a Spacing Scale
  9. Coding taskPractice: Component with Design Tokens
  10. QuestionTokens vs Hardcoded Values
  11. Put in orderFont Size Scale from Smallest
  12. Coding taskPractice: Color Token Preview

Useful articles