การสร้างธีมด้วยตัวแปร CSS
จัดเก็บโทเค็นการออกแบบเป็นคุณสมบัติแบบกำหนดเองของ CSS และอ้างอิงโทเค็นเหล่านั้นในคอนฟิกของ Tailwind เพื่อสลับธีมขณะทำงานได้โดยไม่ต้องคอมไพล์ใหม่
การสร้างธีมด้วยตัวแปร CSS เป็นบทเรียน Tailwind CSS Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Tailwind CSS Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Tailwind CSS Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why CSS Variables for Theming?
CSS custom properties (CSS variables) are the key to runtime theming with Tailwind. Unlike static values baked into the compiled CSS, CSS variables can be changed by JavaScript at any time without reloading the page. This makes them ideal for implementing light/dark mode switches, user-selectable themes, or multi-tenant branding where the same application needs to look different for different clients.
Defining CSS Variables in :root
CSS variables are defined on the :root selector so they are globally available throughout the page. The syntax is --variable-name: value. You reference them with var(--variable-name). Place these definitions in your global CSS file — typically globals.css or index.css — so they are present before any component styles are applied.
/* globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--color-primary: #3b82f6;
--color-primary-hover: #1d4ed8;
--color-surface: #ffffff;
--color-surface-alt: #f8fafc;
--color-text: #111827;
--color-text-muted: #6b7280;
--color-border: #e5e7eb;
}
}Wiring CSS Variables Into Tailwind Config
Once your CSS variables are defined, you reference them in tailwind.config.js using the var(--variable-name) syntax. Tailwind will generate utility classes that use these variables as their values. When the variable changes at runtime, every generated class that references it updates automatically — no recompilation needed.
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'var(--color-primary)',
'primary-hover': 'var(--color-primary-hover)',
surface: 'var(--color-surface)',
'surface-alt': 'var(--color-surface-alt)',
'text-base': 'var(--color-text)',
'text-muted': 'var(--color-text-muted)',
border: 'var(--color-border)'
}
}
}
}Using Variable-Backed Classes in HTML
After wiring variables to Tailwind, your utility classes work exactly as before — the only difference is that the underlying value is now dynamic. Writing bg-surface applies background-color: var(--color-surface) to the element. Switch the variable value in CSS and every element using bg-surface updates without any HTML or JavaScript changes.
<div class="bg-surface text-text-base border border-border rounded-xl p-6">
<h2 class="text-xl font-semibold text-primary mb-2">Card Title</h2>
<p class="text-text-muted text-sm">This card adapts to any theme.</p>
<button class="bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded-lg mt-4">
Action
</button>
</div>Dark Mode With CSS Variables
To implement dark mode, you override the CSS variable values under a .dark class on the root element. When JavaScript toggles the dark class on html, all variable values switch simultaneously, instantly updating every component. This approach requires zero additional Tailwind utilities beyond the initial variable-backed classes you already have.
@layer base {
:root {
--color-primary: #3b82f6;
--color-surface: #ffffff;
--color-text: #111827;
}
.dark {
--color-primary: #60a5fa;
--color-surface: #1e293b;
--color-text: #f1f5f9;
}
}Opacity Support With CSS Variables
There is a subtlety with CSS variable colors and Tailwind's opacity modifier syntax. Utilities like bg-primary/50 require the color to be in RGB channel format so Tailwind can inject the alpha value. To support opacity modifiers, define your variables as RGB triplets without the rgb() wrapper and use the rgb(var() / alpha) pattern in the config.
/* globals.css — RGB triplet format */
:root {
--color-primary-rgb: 59 130 246;
}
/* tailwind.config.js */
module.exports = {
theme: {
extend: {
colors: {
primary: ({
opacityValue
}) => opacityValue
? 'rgb(var(--color-primary-rgb) / ' + opacityValue + ')'
: 'rgb(var(--color-primary-rgb))'
}
}
}
}Multiple Theme Variants
CSS variables allow you to define multiple complete themes beyond just light and dark. Using data-theme attributes, you can scope different variable sets to different parts of the page or switch the entire application theme. This is particularly useful for multi-tenant SaaS applications where each customer brand needs its own color scheme from a shared codebase.
@layer base {
[data-theme='ocean'] {
--color-primary: #0ea5e9;
--color-surface: #0c4a6e;
--color-text: #e0f2fe;
}
[data-theme='forest'] {
--color-primary: #16a34a;
--color-surface: '#dcfce7';
--color-text: #14532d;
}
}
<!-- Switch theme with JS -->
document.documentElement.setAttribute('data-theme', 'ocean');Animating Theme Transitions
When switching themes, a sudden color change can feel jarring. Adding a CSS transition on all properties to the root element creates a smooth color morph effect as variables change. Be selective — transitioning too many properties or using long durations can make the UI feel sluggish. A 150-300ms transition on color-related properties is typically ideal.
/* globals.css */
*, *::before, *::after {
transition-property: color, background-color, border-color;
transition-duration: 200ms;
transition-timing-function: ease;
}
/* Exclude transitions from elements that should be instant */
.no-theme-transition,
.no-theme-transition * {
transition: none !important;
}Persisting Theme Preference
A theme switch is useless if it resets on page reload. Use localStorage to persist the user's preference and restore it on the next visit. The restoration script must run before the page renders to avoid a flash of the wrong theme. Place an inline script at the top of your HTML head — not in a module that loads after painting.
<!-- In <head> before any CSS -->
<script>
(function() {
var theme = localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
if (theme === 'dark') {
document.documentElement.classList.add('dark');
}
})();
</script>Semantic Variable Naming Patterns
Use a consistent naming pattern for your CSS variables to make them predictable and self-documenting. A three-part pattern of --category-role-state works well. For example: --color-action-default, --color-action-hover, --color-surface-raised, --color-feedback-error. Avoid vague names like --color1 or overly specific names like --signup-button-blue.
:root {
/* Action colors */
--color-action-default: #3b82f6;
--color-action-hover: #1d4ed8;
--color-action-disabled: #93c5fd;
/* Surface colors */
--color-surface-base: #ffffff;
--color-surface-raised: #f8fafc;
--color-surface-overlay: #f1f5f9;
/* Feedback colors */
--color-feedback-success: #16a34a;
--color-feedback-error: #dc2626;
--color-feedback-warning: #d97706;
}Debugging CSS Variable Themes
When a themed color is not appearing correctly, the browser DevTools are your best friend. The computed styles panel shows the resolved value of any CSS variable on any element. You can also inspect :root directly to see all variable values. If you are seeing the raw var(--name) string instead of a color, the variable is not defined in the current scope — check for typos or missing :root blocks.
/* Quick debug: visualize all theme colors */
.theme-debug {
background-color: var(--color-surface-base);
color: var(--color-text-primary);
border: 2px solid var(--color-border);
}
/* In DevTools console: */
/* getComputedStyle(document.documentElement)
.getPropertyValue('--color-primary') */Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: CSS custom properties defined on :root serve as dynamic design tokens, Tailwind's config can reference them with var(--name) so generated classes inherit runtime changeability, and multiple themes are implemented by swapping variable values under different class or data-attribute selectors. Next up we explore multi-brand theming strategies for product teams.
คำถามที่พบบ่อย
บทเรียน “การสร้างธีมด้วยตัวแปร CSS” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างธีมด้วยตัวแปร CSS” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Tailwind CSS Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Tailwind CSS Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างธีมด้วยตัวแปร CSS”
จัดเก็บโทเค็นการออกแบบเป็นคุณสมบัติแบบกำหนดเองของ CSS และอ้างอิงโทเค็นเหล่านั้นในคอนฟิกของ Tailwind เพื่อสลับธีมขณะทำงานได้โดยไม่ต้องคอมไพล์ใหม่ คุณปฏิบัติ Tailwind CSS Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Tailwind CSS Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Tailwind CSS Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างธีมด้วยตัวแปร CSS” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Tailwind CSS Academy นี้ได้ไหม
ได้ บทเรียน Tailwind CSS Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- โทเค็นพื้นฐานเทียบกับโทเค็นเชิงความหมาย
- การสร้างธีมด้วยตัวแปร CSS
- กลยุทธ์การสร้างธีมหลายแบรนด์
- เอกสารและการกำกับดูแลโทเค็น