การใช้ตัวแปร CSS ใน Tailwind
กำหนดโทเค็นการออกแบบเป็นคุณสมบัติแบบกำหนดเองของ CSS และอ้างอิงภายในไฟล์กำหนดค่า Tailwind เพื่อสร้างค่าที่ปรับตามธีมได้
การใช้ตัวแปร CSS ใน Tailwind เป็นบทเรียน Tailwind CSS Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Tailwind CSS Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Tailwind CSS Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
CSS Custom Properties as Design Tokens
CSS custom properties (also called CSS variables) let you define values once and reference them throughout your stylesheet. They are runtime values — they can be changed by JavaScript or by switching a class on a parent element. Combining CSS variables with Tailwind's config creates a powerful theming system: design tokens live in CSS variables, and Tailwind generates utility classes that reference those variables.
/* CSS variables defined in :root */
:root {
--color-primary: #6366f1;
--color-surface: #ffffff;
--color-on-surface: #111827;
--spacing-section: 5rem;
}
/* Dark mode swaps values without changing class names */
.dark {
--color-surface: #1f2937;
--color-on-surface: #f9fafb;
}Referencing CSS Variables in Tailwind Config
Wire CSS variables into Tailwind's config using the var(--variable-name) syntax as the value. This creates utility classes that output var() references in the generated CSS. At runtime, when the variable value changes (such as in dark mode or on theme switch), all elements using those utility classes update instantly without rebuilding the CSS or toggling additional classes.
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'var(--color-primary)',
surface: 'var(--color-surface)',
'on-surface': 'var(--color-on-surface)',
},
spacing: {
section: 'var(--spacing-section)',
},
},
},
};The alpha-value Placeholder for Opacity
When you want opacity modifier support (bg-primary/50) for CSS variable colors, Tailwind needs to know how to apply opacity. The trick is to store colors as space-separated RGB channel values and use the <alpha-value> placeholder in the config. Tailwind replaces this placeholder with the opacity fraction at compile time, generating correct rgba() or rgb(... / alpha) syntax.
/* CSS: store as RGB channels, not hex */
:root {
--color-primary: 99 102 241; /* R G B without rgb() wrapper */
}
.dark {
--color-primary: 129 140 248; /* lighter shade for dark mode */
}
/* tailwind.config.js */
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
}
<!-- Now opacity modifier works -->
<div class="bg-primary/50"> <!-- 50% opacity primary background -->Automatic Dark Mode With CSS Variables
The most elegant use of CSS variables in Tailwind is automatic dark mode without dark: prefixes everywhere. Define your semantic tokens (surface, text, border) as CSS variables and change their values in the .dark selector. Components using bg-surface automatically get the dark background — no extra classes needed on individual elements. This drastically reduces the amount of markup needed for dark mode.
/* CSS */
:root {
--surface: 255 255 255; /* white */
--on-surface: 17 24 39; /* gray-900 */
}
.dark {
--surface: 31 41 55; /* gray-800 */
--on-surface: 249 250 251; /* gray-50 */
}
<!-- tailwind.config.js adds: bg-surface, text-on-surface -->
<!-- HTML: no dark: prefix needed! -->
<div class="bg-surface text-on-surface p-6 rounded-xl">
Automatically adapts to dark mode via CSS variable swap
</div>Multi-Theme Switching at Runtime
CSS variables enable multiple themes beyond just light and dark. Define a set of CSS variables for each theme and apply different sets by toggling a data-theme attribute or class on the root element. Users can switch from your default blue theme to a green or high-contrast theme instantly, with all Tailwind utilities that reference those variables updating in real time.
/* Multiple brand themes using data-theme */
:root, [data-theme='blue'] {
--color-accent: 99 102 241;
}
[data-theme='green'] {
--color-accent: 22 163 74;
}
[data-theme='orange'] {
--color-accent: 234 88 12;
}
<!-- Toggle themes with JavaScript -->
<script>
document.documentElement.setAttribute('data-theme', 'green');
</script>Using the theme() Function in CSS
Inside CSS files processed by Tailwind, the special theme() function lets you reference Tailwind theme values directly. Use it in custom CSS rules or @layer blocks to access your configured colors, spacing, and typography values. This is the inverse of the previous pattern — instead of CSS variables in the Tailwind config, you bring Tailwind token values into your CSS.
/* Using theme() function in CSS */
@layer components {
.btn-primary {
background-color: theme('colors.blue.600');
padding: theme('spacing.3') theme('spacing.6');
border-radius: theme('borderRadius.lg');
font-weight: theme('fontWeight.semibold');
color: theme('colors.white');
}
.btn-primary:hover {
background-color: theme('colors.blue.700');
}
}Combining CSS Variables and @apply
You can combine CSS variables with @apply in your custom CSS layers. Define a component class using @apply for most utilities, then use CSS variables for the values that need to change at runtime. This hybrid approach keeps your HTML lean while still enabling dynamic theming for the values that matter most to your design system.
@layer components {
.card {
@apply rounded-xl border p-6 shadow-sm;
background-color: rgb(var(--surface) / 1);
color: rgb(var(--on-surface) / 1);
border-color: rgb(var(--border) / 1);
}
.card-header {
@apply font-semibold text-lg mb-4 pb-4;
border-bottom: 1px solid rgb(var(--border) / 1);
}
}CSS Variables for Typography Tokens
Typography tokens like font size, line height, and letter spacing can also be defined as CSS variables and referenced in Tailwind's config. This enables responsive typography where JavaScript adjusts font-size variables based on viewport conditions, or a11y-friendly font scaling where users can increase text size and the variables cascade through the entire design system automatically.
/* Typography tokens as CSS variables */
:root {
--font-size-base: 1rem;
--font-size-lg: 1.125rem;
--font-size-xl: 1.25rem;
--line-height-normal: 1.5;
--font-weight-heading: 700;
}
/* tailwind.config.js */
theme: {
extend: {
fontSize: {
'token-base': 'var(--font-size-base)',
'token-lg': 'var(--font-size-lg)',
},
},
}Browser Support Considerations
CSS custom properties are supported in all modern browsers (Chrome, Firefox, Safari, Edge). They are NOT supported in Internet Explorer 11. If your project must support IE11, CSS variables cannot be used for theming. For all other projects (which is the vast majority today), CSS variables are a safe and powerful choice with excellent browser adoption across the global user base.
/* CSS variables work in all modern browsers */
/* Browser support: Chrome 49+, Firefox 31+, Safari 9.1+, Edge 15+ */
/* For IE11 fallback (if required): */
.button {
background-color: #6366f1; /* IE11 fallback */
background-color: var(--color-primary); /* modern browsers override above */
}Inspecting CSS Variables in DevTools
CSS variables are easy to inspect and debug in browser DevTools. Select any element and look at its Computed tab — you will see the resolved values of any CSS variables in play. The Elements panel shows the variable declaration in the cascade. You can even override CSS variable values directly in DevTools to preview theme changes without modifying code, which is excellent for rapid iteration on design tokens.
CSS Variables vs Config Values: When to Use Which
Use static config values for design tokens that never change at runtime — spacing scale, border radius scale, breakpoints, and font size scale. Use CSS variables for tokens that change based on theme, user preference, or runtime context — colors, surface backgrounds, text colors, and semantic design tokens. This division keeps the parts of your design system that vary at runtime in CSS, and the structural layout rules in the config where they are processed at build time.
Quick Check
Test your understanding of using CSS variables in Tailwind CSS.
Lesson Recap
In this lesson you learned: CSS variables in Tailwind's config create runtime-swappable design tokens, use the <alpha-value> placeholder with RGB channel variables for opacity modifier support, and semantic CSS variables swapped in a .dark or [data-theme] selector enable automatic theming without per-element dark: classes. Next up we dive into the @apply directive for extracting repeated utility patterns.
คำถามที่พบบ่อย
บทเรียน “การใช้ตัวแปร CSS ใน Tailwind” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การใช้ตัวแปร CSS ใน Tailwind” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Tailwind CSS Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Tailwind CSS Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การใช้ตัวแปร CSS ใน Tailwind”
กำหนดโทเค็นการออกแบบเป็นคุณสมบัติแบบกำหนดเองของ CSS และอ้างอิงภายในไฟล์กำหนดค่า Tailwind เพื่อสร้างค่าที่ปรับตามธีมได้ คุณปฏิบัติ Tailwind CSS Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Tailwind CSS Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Tailwind CSS Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การใช้ตัวแปร CSS ใน Tailwind” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Tailwind CSS Academy นี้ได้ไหม
ได้ บทเรียน Tailwind CSS Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเพิ่มสีแบบกำหนดเอง
- ตระกูลฟอนต์แบบกำหนดเอง
- ค่าระยะห่างแบบกำหนดเอง
- การใช้ตัวแปร CSS ใน Tailwind