1. guides
  2. โ€บ
  3. Cookbook
  4. โ€บ
  5. light switch

Light Switch

Learn how to create a Light Switch toggle.

Use Dark Mode to make use of either a base or dark: variant for your utility class styles. By default, Tailwind uses the prefers-color-scheme media query to determine and match the userโ€™s operating system settings. However, if you wish to provide your users manual control, youโ€™ll need to adjust the Dark Mode strategy for Tailwind, as well as provide the toggle interface (aka a light switch). This guide will show you how to fulfill both requirements.

1

Adjust the Dark Mode Strategy

Open your global stylesheet and set the following variant:

@custom-variant dark (&:where([data-mode="dark"], [data-mode="dark"] *));

Then set the following data attribute on your applicationโ€™s <html> element for light mode:

<html data-mode="light"></html>

Or for dark mode:

<html data-mode="dark"></html>
2

Create the Component

Weโ€™ll create a implementation of the Switch component that can toggle the mode on demand.

3

Import the Component

Weโ€™ll then add the component to our app. Make sure to set the correct path and file extension.

import Lightswitch from './path/to/Lightswitch.{tsx|svelte}';
<Lightswitch />

User Interface

While we utilize a primitive Switch for the minimal example above, feel free to adjust the logic and interface to your preference. We provide a more detailed Switch example for React and Svelte respectively.

Next.js Users

For Next.js users, you will need to suppressHydrationWarning to true on the root <html> element. This will suppress hydration warnings.