Design tokens với CSS custom properties: Hệ thống design scalable
CSS custom properties kết hợp design tokens tạo nên hệ thống design linh hoạt, dễ maintain và scale. Cách tổ chức tokens cho dự án thực tế.
Design tokens không chỉ là trend — đây là foundation của mọi design system nghiêm túc. Và CSS custom properties (CSS variables) là cách native, zero-dependency để implement chúng trên web.
Design tokens là gì?
Design tokens là các primitive values đại diện cho design decisions: colors, spacing, typography, shadows, borders. Thay vì hardcode #3b82f6 khắp nơi, bạn dùng --color-primary. Token là single source of truth giữa design và code.
Tổ chức token layers
Mình tổ chức tokens theo 3 layers:
/* Layer 1: Primitive tokens — raw values */
:root {
--blue-50: oklch(97% 0.02 250);
--blue-500: oklch(65% 0.25 260);
--blue-900: oklch(30% 0.12 260);
--gray-50: oklch(98% 0.005 260);
--gray-900: oklch(20% 0.02 260);
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-4: 1rem;
--space-8: 2rem;
--radius-sm: 0.375rem;
--radius-md: 0.5rem;
--radius-lg: 1rem;
}
/* Layer 2: Semantic tokens — design decisions */
:root {
--color-primary: var(--blue-500);
--color-bg: var(--gray-50);
--color-text: var(--gray-900);
--color-surface: white;
--color-border: oklch(90% 0.01 260);
--spacing-section: var(--space-8);
--spacing-card: var(--space-4);
--radius-card: var(--radius-md);
--radius-button: var(--radius-sm);
}
/* Layer 3: Component tokens */
.card {
--card-padding: var(--spacing-card);
--card-radius: var(--radius-card);
--card-bg: var(--color-surface);
--card-shadow: 0 1px 3px oklch(0% 0 0 / 0.1);
}
Dark mode với token swap
Đây là lúc tokens thể hiện sức mạnh — dark mode chỉ cần swap semantic layer:
@media (prefers-color-scheme: dark) {
:root {
--color-primary: var(--blue-400, oklch(75% 0.2 260));
--color-bg: var(--gray-900);
--color-text: var(--gray-50);
--color-surface: oklch(25% 0.02 260);
--color-border: oklch(35% 0.02 260);
}
}
/* Hoặc class-based toggle */
[data-theme="dark"] {
--color-bg: var(--gray-900);
--color-text: var(--gray-50);
--color-surface: oklch(25% 0.02 260);
}
Không cần đổi một dòng CSS nào trong components. Tất cả components tự adapt vì chúng reference semantic tokens.
Tips thực tế
- Naming convention: dùng pattern
--{category}-{property}-{variant}— ví dụ--color-text-muted,--space-inline-sm. - Fallback values: luôn có fallback cho critical tokens —
var(--color-primary, #3b82f6). - Scope tokens: component tokens nên scoped trong selector, không global.
- Đừng over-tokenize: không phải mọi value đều cần token. One-off values thì hardcode.
Kết
CSS custom properties là cách đơn giản nhất để implement design tokens. Ba layers (primitive → semantic → component) giữ system organized khi scale. Kết hợp với native dark mode và Container Queries, bạn có một design system mạnh mẽ mà không cần thêm tooling.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!