Tailwind CSS - 深色模式


深色模式是許多作業系統中的一項功能,它將螢幕的配色方案更改為較暗的色調。它在低光照條件下提高了可見性,並與傳統的明亮主題相比,提供了更柔和的觀看體驗。

Tailwind CSS簡化了在您的網站上實現深色模式的過程。它提供了一個內建的深色模式變體,允許您輕鬆地為亮色和深色主題設定網站樣式。

您可以使用Tailwind 的深色變體定義深色模式的特定樣式,確保您的網站在亮色和深色設定下都能看起來很棒。

示例

<!DOCTYPE html>
<html lang="en" class="dark">
<head>
  <script src="https://cdn.tailwindcss.com"></script>
</head> 

<body class="bg-gray-200 p-4">
    <div class="grid grid-cols-2 gap-6">
        <!-- Light Mode Card -->
        <div class="bg-white p-6 rounded-lg shadow-xl">
            <h2 class="text-xl font-semibold mb-2 text-gray-800">
                Light Mode
            </h2>
            <p class="text-gray-600">
                This is the light mode version of the card. 
                The background is white, and the text is in 
                shades of gray, offering a clean and bright 
                appearance.
            </p>
        </div>
        <!-- Dark Mode Card -->
        <div class="bg-gray-900 p-6 rounded-lg shadow-xl">
            <h2 class="text-xl font-semibold mb-2 text-gray-100">
                Dark Mode
            </h2>
            <p class="text-gray-400">
                This is the dark mode version of the card. 
                The background is dark gray, and the text 
                is in lighter shades, making it easier to 
                read in low-light conditions.
            </p>
        </div>
    </div>
</body>

</html>

此示例顯示了卡片元件在亮色模式深色模式下的外觀,並排顯示。亮色模式卡片具有白色背景和深色文字,而深色模式卡片具有深色背景和淺色文字,便於閱讀。

使用 Tailwind CSS 手動切換深色模式

要在您的 Tailwind CSS 專案中手動控制深色模式,您可以使用“選擇器”策略,而不是依賴系統的預設設定來處理深色模式。以下是配置方法。

在您的tailwind.config.js檔案中,設定深色模式如下:

module.exports = {
  darkMode: 'selector',
  // ...
}

透過此設定,當元素上存在特定類(例如,dark)時,將應用深色模式樣式,而不是依賴使用者的系統設定。

示例:無深色模式

<html>
<body>
    <!-- This will be white -->
    <div class="bg-white dark:bg-black">
        <!-- ... -->
    </div>
</body>

</html>

示例:啟用深色模式

<html class="dark">
<body>
    <!-- This will be black -->
    <div class="bg-white dark:bg-black">
        <!-- ... -->
    </div>
</body>
</html>

如果您在Tailwind 配置中使用了字首,請確保將其應用於深色模式類。例如,使用像tw-這樣的字首,您應該使用tw-dark來啟用深色模式。此外,為了管理何時應用 dark 類,您可以使用 JavaScript 檢查使用者首選項(例如來自localStorage)並相應地更新 HTML。

自定義深色模式選擇器

在某些框架中,深色模式的處理方式不同,使用唯一的類名或方法。Tailwind CSS允許您透過在配置中定義自定義選擇器來自定義深色模式的應用方式。

您可以透過使用陣列配置darkMode來設定自定義選擇器,如下所示:

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: ['selector', '[data-mode="dark"]'],
  // ...
}

Tailwind 將使用:where()偽類包裝您的自定義選擇器,以確保其特異性與基於媒體的預設策略匹配。

.dark\:underline:where([data-mode="dark"], [data-mode="dark"] *) {
  text-decoration-line: underline;
}

同時支援系統首選項和手動選擇

您可以使用選擇器策略來同時支援系統首選項和手動主題切換。此示例顯示瞭如何使用localStoragewindow.matchMedia() API 來管理主題。

// Check and apply the theme on page load
if (localStorage.theme === 'dark' || (!('theme' in localStorage) 
    && window.matchMedia('(prefers-color-scheme: dark)').matches)) 
{
  document.documentElement.classList.add('dark');
} else {
  document.documentElement.classList.remove('dark');
}

// To set light mode
localStorage.theme = 'light';

// To set dark mode
localStorage.theme = 'dark';

// To respect the OS preference
localStorage.removeItem('theme');

您可以完全靈活地實現這一點,無論您選擇在客戶端管理首選項還是將它們儲存在伺服器上並在頁面呈現期間應用它們。

自定義深色模式變體

如果您更願意使用您自己的深色模式變體而不是Tailwind 的預設變體,您可以在您的tailwind.config.js檔案中對其進行自定義。要設定自定義深色模式變體,請使用以下配置。

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: ['variant', '&:not(.light *)'],
  // ...
}

使用此方法,Tailwind 不會更改您提供的選擇器。因此,請注意其特異性,並考慮使用:where()偽類來匹配其他 Tailwind 實用程式的特異性。

使用多個選擇器

如果您需要適應不同的場景來啟用深色模式,可以在配置檔案中陣列內指定多個選擇器。

/** @type {import('tailwindcss').Config} */
module.exports = {
    darkMode: ['variant', [
    '@media (prefers-color-scheme: dark) { &:not(.light *) }',
    '&:is(.dark *)',
    ]],
    // ...
}

此配置允許您透過指定多個選擇器來處理各種深色模式用例。

廣告