Sub topic 1
Styling for dark mode with the `dark:` variant
Prerequisites
Assume you know basic HTML and CSS, Tailwind utility classes, and JavaScript DOM syntax. Tailwind is already installed in your project.
Styling for dark mode with the `dark:` variant
Tailwind's dark: variant applies a utility only when dark mode is active. Add a light utility first, then add its dark replacement:
<div class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Account settings</h1>
<p class="text-gray-600 dark:text-gray-300">
Choose how your account behaves.
</p>
</div>The unprefixed classes define the default appearance. The dark: classes override those values in dark mode. You usually need to adjust surfaces, text, borders, icons, and focus states together.
Default behavior: following the operating system
By default, Tailwind uses the browser's prefers-color-scheme media feature. The browser reports whether the operating system prefers light or dark mode, and Tailwind activates dark: accordingly.
This strategy requires no JavaScript. It keeps the page synchronized with the operating system, but users cannot choose a different theme inside your application.
Taking control with a class or selector
A manual strategy makes dark mode depend on your markup. For example, a .dark class on the root element can activate dark styles for every descendant:
<html class="dark">
<body class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<main>Dark mode is active.</main>
</body>
</html>Your application can add or remove that class when a user selects a theme. A data attribute works similarly:
<html data-theme="dark">
<body class="bg-white dark:bg-gray-900">
<main>Dark mode is active.</main>
</body>
</html>The exact configuration differs between Tailwind versions. Tailwind v3 uses the darkMode setting. Tailwind v4 redefines the dark variant in CSS. Configure this before writing the toggle logic; otherwise the class may change without affecting any utilities.
Exercise
What does dark:bg-gray-900 do when dark mode is inactive?
Show answer
It has no effect. The element keeps its other background utility, such as bg-white.