Tailwind CSSでダークモードを実装する
ダークモードの重要性
最近のWebアプリケーションでは、ダークモードの実装が標準的になってきました。ユーザーの目の疲れを軽減し、バッテリー消費を抑えるなど、多くのメリットがあります。
Tailwind CSSでの実装
Tailwind CSSでは、dark: バリアントを使用することで簡単にダークモードを実装できます。
1. 設定ファイルの更新
// tailwind.config.js
module.exports = {
darkMode: 'class', // または 'media'
// ...
}
2. HTMLクラスの切り替え
// テーマ切り替えの実装
function toggleTheme() {
document.documentElement.classList.toggle('dark');
}
3. スタイルの適用
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
<h1 class="text-2xl font-bold">ダークモード対応のタイトル</h1>
<p class="text-gray-700 dark:text-gray-300">
ライトモードとダークモードで色が変わります。
</p>
</div>
カラーパレットの選び方
ダークモードでは、単に色を反転させるだけでなく、適切なコントラストを保つことが重要です。
おすすめのカラー設定
- 背景色:
gray-900またはgray-950 - テキスト:
gray-100またはwhite - サブテキスト:
gray-400 - ボーダー:
gray-700またはgray-800
ユーザー設定の保存
ユーザーの選択を記憶するために、localStorageを使用します:
// テーマの保存と読み込み
const theme = localStorage.getItem('theme') || 'light';
if (theme === 'dark') {
document.documentElement.classList.add('dark');
}
// 切り替え時に保存
function toggleTheme() {
const isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
まとめ
Tailwind CSSを使えば、ダークモードの実装は驚くほど簡単です。ユーザビリティを向上させるためにも、ぜひ実装してみてください。