0Pricing
Tailwind CSS Academy · 강의

토큰 및 설정 계층 구축

디자인 토큰을 CSS 변수로 구현하고 Tailwind 설정에 연결한 다음, 라이트 모드와 다크 모드에서 테스트합니다.

토큰 및 설정 계층 구축은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Token Layer Overview

The token layer is the bridge between your design decisions and Tailwind's utility generation. It consists of CSS custom properties (design tokens at the CSS level) and the Tailwind config that references those properties. When implemented correctly, swapping a theme requires only changing the CSS variable values — no Tailwind class names change, no component code changes.

Defining Primitive Tokens

Start by defining all raw color, spacing, and typography values in a tokens/primitives.css file using CSS custom properties. These primitives are not used directly by components — they exist only to feed the semantic token layer. Use a structured naming convention like --color-blue-500 for colors and --space-4 for spacing values.

/* tokens/primitives.css */
:root {
  /* Color primitives */
  --color-blue-50: #eff6ff;
  --color-blue-100: #dbeafe;
  --color-blue-500: #3b82f6;
  --color-blue-600: #2563eb;
  --color-blue-700: #1d4ed8;
  --color-blue-900: #1e3a8a;

  --color-gray-50: #f9fafb;
  --color-gray-100: #f3f4f6;
  --color-gray-500: #6b7280;
  --color-gray-900: #111827;

  --color-white: #ffffff;
  --color-black: #000000;

  /* Spacing primitives */
  --space-1: 0.25rem;
  --space-4: 1rem;
  --space-8: 2rem;
}

Defining Semantic Tokens

Semantic tokens give meaning to primitive values. Define them in a separate tokens/semantic.css file. Each semantic token references a primitive token and represents a purpose rather than a value. The same semantic token is overridden in a dark mode scope or a different brand scope to achieve theme switching.

/* tokens/semantic.css */
:root {
  /* Brand colors */
  --color-primary:       var(--color-blue-600);
  --color-primary-hover: var(--color-blue-700);
  --color-primary-light: var(--color-blue-50);

  /* Surface colors */
  --color-surface:         var(--color-white);
  --color-surface-elevated: var(--color-gray-50);

  /* Text colors */
  --color-text-primary:   var(--color-gray-900);
  --color-text-secondary: var(--color-gray-500);

  /* Border colors */
  --color-border: var(--color-gray-100);
}

Dark Mode Token Override

Override semantic tokens under the .dark class (for class strategy) or @media (prefers-color-scheme: dark) (for media strategy). Only semantic tokens change — primitive definitions remain unchanged. This is the power of the two-tier system: dark mode is implemented entirely in the token layer, with zero changes to component CSS or Tailwind classes.

/* tokens/semantic.css (dark mode overrides) */
:root {
  --color-surface: #ffffff;
  --color-text-primary: #111827;
  --color-border: #f3f4f6;
}

.dark {
  --color-surface: #111827;        /* was white */
  --color-text-primary: #f9fafb;   /* was dark gray */
  --color-border: #1f2937;         /* was light gray */
  --color-surface-elevated: #1f2937;
  /* --color-primary unchanged: blue works in both modes */
}

Wiring Tokens Into Tailwind Config

Reference CSS custom properties inside the Tailwind config's theme extension. Use var(--token-name) as the value. This means every Tailwind utility that references the theme token will use the CSS variable at runtime, enabling live theme switching without recompilation. The JIT engine generates classes with var() values in the output CSS.

// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: {
          DEFAULT: 'var(--color-primary)',
          hover: 'var(--color-primary-hover)',
          light: 'var(--color-primary-light)',
        },
        surface: 'var(--color-surface)',
        'text-primary': 'var(--color-text-primary)',
        'text-secondary': 'var(--color-text-secondary)',
        border: 'var(--color-border)',
      },
    },
  },
};

Using Token-Based Utilities in Components

With tokens wired into the config, you use them like any other Tailwind color. bg-surface applies the --color-surface CSS variable as a background. When the user switches to dark mode, the CSS variable value changes, and the background updates automatically without any component changes. Token-based classes look identical to built-in Tailwind classes in the markup.

<!-- Token-based Tailwind classes look just like built-in ones -->
<div class="bg-surface border border-border rounded-xl p-6">
  <h2 class="text-text-primary font-semibold">Card Title</h2>
  <p class="mt-2 text-text-secondary text-sm">Card description</p>
  <button class="mt-4 rounded-lg bg-primary px-4 py-2 font-semibold text-white
                 hover:bg-primary-hover transition">
    Primary Action
  </button>
</div>

Typography Tokens

Define font family, font size, line height, and font weight as tokens. Font families should reference a CSS variable so switching brand typefaces requires only a variable change. Font sizes can be extended in the Tailwind config with semantic names like text-display and text-caption alongside the default numeric scale.

/* tokens/semantic.css */
:root {
  --font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
  --font-display: 'Cal Sans', var(--font-sans);
  --font-mono: 'JetBrains Mono', ui-monospace, monospace;
}

// tailwind.config.js
theme: {
  extend: {
    fontFamily: {
      sans: ['var(--font-sans)'],
      display: ['var(--font-display)'],
      mono: ['var(--font-mono)'],
    },
    fontSize: {
      display: ['3.75rem', { lineHeight: '1.1', fontWeight: '700' }],
      caption: ['0.75rem', { lineHeight: '1.5' }],
    },
  },
},

Spacing and Radius Tokens

Extend the spacing and border radius scales with semantic names for component-level constants. Rather than remembering that cards use rounded-xl and badges use rounded-full, define radius.card: xl and radius.badge: full in the config. This makes component code self-documenting and ensures all cards use the same radius even when the value changes.

// tailwind.config.js
theme: {
  extend: {
    borderRadius: {
      card:  '0.75rem',   // 12px — used by Card, Dialog
      input: '0.5rem',    // 8px  — used by Input, Select
      badge: '9999px',    // pill — used by Badge, Tag
      button: '0.5rem',   // 8px  — used by all Button variants
    },
    spacing: {
      18: '4.5rem',
      22: '5.5rem',
      128: '32rem',
    },
  },
},

Shadow Tokens

Define consistent shadow levels in the Tailwind config using semantic names. Shadows communicate visual hierarchy: none for flat elements, card for surface elements, elevated for dropdowns and modals, focus for interactive state indicators. This prevents arbitrary shadow values scattered across the codebase.

// tailwind.config.js
theme: {
  extend: {
    boxShadow: {
      card:     '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)',
      elevated: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',
      focus:    '0 0 0 3px var(--color-primary-light)',
    },
  },
},

<!-- Use semantic shadow names -->
<div class="shadow-card hover:shadow-elevated transition-shadow">

Validating Tokens in CI

Add a CI step that validates token integrity — checking that every semantic token references a primitive that exists, and that no semantic token is a raw hex value (which would bypass the two-tier system). A simple Node.js script that parses the CSS variable file and checks references can catch token drift before it reaches production.

// scripts/validate-tokens.js
const fs = require('fs');
const semanticCss = fs.readFileSync('tokens/semantic.css', 'utf8');
const primitiveCss = fs.readFileSync('tokens/primitives.css', 'utf8');

// Extract all var() references in semantic.css
const refs = [...semanticCss.matchAll(/var\(([^)]+)\)/g)].map(m => m[1].trim());

// Check each ref exists in primitives.css
const missing = refs.filter(ref => !primitiveCss.includes(ref + ':'));
if (missing.length > 0) {
  console.error('Undefined primitive tokens:', missing);
  process.exit(1);
}
console.log('All tokens valid.');

Testing Dark Mode Token Switching

Test dark mode visually at the token level by toggling the .dark class on html and verifying that every semantic color surface, text, and border renders correctly. Use Playwright or Cypress to take screenshots with dark applied and compare against light mode baselines. Run this test suite whenever the token file changes to catch visual regressions immediately.

// playwright/dark-mode.spec.ts
import { test, expect } from '@playwright/test';

test('tokens switch correctly in dark mode', async ({ page }) => {
  await page.goto('/tokens-preview');

  // Light mode screenshot
  await expect(page).toHaveScreenshot('tokens-light.png');

  // Enable dark mode
  await page.evaluate(() =>
    document.documentElement.classList.add('dark')
  );

  // Dark mode screenshot
  await expect(page).toHaveScreenshot('tokens-dark.png');
});

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: defining primitive and semantic tokens as CSS custom properties in separate files, wiring semantic tokens into the Tailwind config using var() so they update at runtime, and implementing dark mode by overriding only semantic tokens under the .dark class. Next up we build the component library using these tokens.

자주 묻는 질문

“토큰 및 설정 계층 구축” 강의는 무료인가요?

네 — “토큰 및 설정 계층 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“토큰 및 설정 계층 구축”에서 뭘 배우나요?

디자인 토큰을 CSS 변수로 구현하고 Tailwind 설정에 연결한 다음, 라이트 모드와 다크 모드에서 테스트합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“토큰 및 설정 계층 구축” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 디자인 시스템 계획하기
  2. 토큰 및 설정 계층 구축
  3. 컴포넌트 라이브러리 구축
  4. 문서화 및 팀 인계
← Tailwind CSS Academy(으)로 돌아가기