ป้ายกำกับ: Semantic Design Tokens

Dynamic Dark/Light Theme with Tailwind CSS & CSS Custom PropertiesDynamic Dark/Light Theme with Tailwind CSS & CSS Custom Properties

The traditional method of implementing Dark Mode with Tailwind CSS involves writing paired classes, such as bg-white dark:bg-slate-900 text-slate-800 dark:text-slate-100. This approach works well for small projects but can lead to issues as the system grows:

  • Verbose and repetitive code, requiring the dark: prefix to be added to every component.
  • Risk of developers selecting color pairs that fail the WCAG Contrast AA standard in one mode.
  • Lack of flexibility if additional themes (e.g., High Contrast Theme or Brand Theme) need to be added in the future.

The optimal solution for enterprise-level projects is to create Semantic Design Tokens using CSS Variables in conjunction with Tailwind CSS. This approach keeps HTML classes clean, allowing for calls like bg-surface text-content-main, with CSS Variables automatically switching color values and maintaining contrast levels that pass the AA standard.


Setting CSS Variables (Color Channels for Opacity Support)

A common limitation when integrating CSS Variables with Tailwind is that utility classes for adjusting opacity (e.g., bg-surface/80) often don’t work. The solution is to store color values as RGB or HSL Channels without wrapping them in functions in the globals.css file.

SQL

:root {  --surface: 255, 255, 255;  --content-main: 0, 0, 0;  --surface-dark: 30, 30, 30;  --content-main-dark: 255, 255, 255;}

With this setup, you can easily adjust opacity using Tailwind’s utility classes:

SQL

<div class="bg-surface/80 text-content-main">Content</div>

Conclusion

Implementing a dynamic Dark/Light theme using Tailwind CSS and CSS Custom Properties offers a clean, scalable, and maintainable solution. By leveraging semantic design tokens and CSS Variables, developers can create a system that not only supports Dark and Light modes but also easily accommodates additional themes in the future. This approach ensures consistent contrast levels and reduces the risk of errors in color selection.