SCALE — Build Lab
開発パターン · CSS PATTERN

Tailwind v4 CSS変数テーマ

CATEGORY開発パターン TYPECSS Pattern EFFORT60〜180分 DIFFICULTY
PRIMARY CODE
css
/* === app/globals.css === */
@import "tailwindcss";

/* Tailwind v4 のテーマ拡張は @theme で */
@theme {
  --color-bg:     #0a0a0e;
  --color-bg2:    #131319;
  --color-bg3:    #1a1a22;
  --color-text:   #f4f4f5;
  --color-text2:  #a1a1aa;
  --color-border: #27272a;
}

/* ライトモード(class="light" を <html> に付与で切替) */
.light {
  --color-bg:     #ffffff;
  --color-bg2:    #f4f4f5;
  --color-bg3:    #e4e4e7;
  --color-text:   #18181b;
  --color-text2:  #52525b;
  --color-border: #d4d4d8;
}

/* === ThemeToggle.tsx === */
'use client';
import { useEffect, useState } from 'react';

export function ThemeToggle() {
  const [light, setLight] = useState(false);
  useEffect(() => {
    const saved = localStorage.getItem('theme') === 'light';
    setLight(saved);
    document.documentElement.classList.toggle('light', saved);
  }, []);
  return (
    <button onClick={() => {
      const next = !light;
      setLight(next);
      document.documentElement.classList.toggle('light', next);
      localStorage.setItem('theme', next ? 'light' : 'dark');
    }}>
      {light ? '🌙' : '☀️'}
    </button>
  );
}
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 全ダッシュボード

Tailwind v4 CSS変数テーマ

:LiTarget: 用途

Tailwind v4 でダーク/ライトモードをCSS変数で切り替えるパターン。

:LiSparkle: 特徴

  • CSS変数
  • ダーク/ライト切替
  • カスタムカラー対応

:LiCode: コード(コピペ用)

/* === app/globals.css === */
@import "tailwindcss";

/* Tailwind v4 のテーマ拡張は @theme で */
@theme {
  --color-bg:     #0a0a0e;
  --color-bg2:    #131319;
  --color-bg3:    #1a1a22;
  --color-text:   #f4f4f5;
  --color-text2:  #a1a1aa;
  --color-border: #27272a;
}

/* ライトモード(class="light" を <html> に付与で切替) */
.light {
  --color-bg:     #ffffff;
  --color-bg2:    #f4f4f5;
  --color-bg3:    #e4e4e7;
  --color-text:   #18181b;
  --color-text2:  #52525b;
  --color-border: #d4d4d8;
}

/* === ThemeToggle.tsx === */
'use client';
import { useEffect, useState } from 'react';

export function ThemeToggle() {
  const [light, setLight] = useState(false);
  useEffect(() => {
    const saved = localStorage.getItem('theme') === 'light';
    setLight(saved);
    document.documentElement.classList.toggle('light', saved);
  }, []);
  return (
    <button onClick={() => {
      const next = !light;
      setLight(next);
      document.documentElement.classList.toggle('light', next);
      localStorage.setItem('theme', next ? 'light' : 'dark');
    }}>
      {light ? '🌙' : '☀️'}
    </button>
  );
}

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加