เมนู
ในหน้านี้

Theme System (Dark/Light Mode)

สร้างระบบ theme ด้วย CSS variables และ next-themes สำหรับ dark/light mode

ระบบ theme ใช้ CSS variables เพื่อความยืดหยุ่น และ next-themes สำหรับสลับ dark/light mode อย่างราบรื่น CSS variables ช่วยให้เปลี่ยน theme ได้ทันทีโดยไม่ต้อง re-render components — แค่เปลี่ยนค่า variable next-themes จัดการตรวจจับ system preference, เก็บใน localStorage และป้องกันการ flash ของ theme ผิดตอนโหลดหน้า ผมกำหนด color tokens เป็นค่า HSL ซึ่งทำให้สร้าง color palettes ที่สม่ำเสมอได้ง่าย และปรับ lightness สำหรับ states ต่างๆ (hover, active, ฯลฯ)

ผมใช้ next-themes + CSS variables เพราะความง่ายและ integration กับ Next.js หรือคุณอาจ implement theme switching ด้วย React Context, Zustand หรือ CSS-in-JS solutions เช่น styled-components หรือ Emotion รูปแบบ CSS variables ใช้ได้กับทุกวิธี — สิ่งสำคัญคือการกำหนด semantic color tokens ที่ปรับตามแต่ละ theme

วิธีการทำงาน

lib/
└── providers/
    └── theme-provider.tsx    # Theme provider wrapper

components/
└── common/
    └── ThemeToggle.tsx       # Theme toggle button

styles/
└── globals.css               # CSS variables for themes

tailwind.config.ts            # Tailwind theme configuration
app/
└── layout.tsx                # Root layout with provider

CSS Variables

Use HSL color format for easy theme customization and consistent colors.

Class-based

Using Tailwind's class strategy with next-themes for seamless switching.

System Preference

Auto detect and apply user's OS theme preference.

No Flash

Prevents flash of unstyled content with suppressHydrationWarning.

คุณสมบัติหลัก

  • CSS variables สำหรับ theming ที่ยืดหยุ่น
  • System preference detection
  • Persistent theme selection
  • No flash on page load
  • ง่ายต่อการเพิ่ม theme ใหม่

ตัวอย่างการใช้งาน

Theme Switcher Demo

ตัวอย่าง

Card Title

This is how your content looks in light mode.

Color Palette

Primary
Background
Foreground
Card