Sub topic 3
Taking Control with a Class or Selector
This chapter covers the manual dark mode strategy. You will see why it exists, how it changes what dark: compiles to, and how to configure it in Tailwind v3 and v4. The chapter assumes you know basic HTML and CSS, Tailwind utility classes and variants such as hover: and md:, and basic JavaScript (the DOM and localStorage). It also assumes a project with Tailwind already installed. The toggle script and persistence come in later chapters. Here the goal is to get the CSS side right.
Why the default is not enough
By default, dark: follows the operating system. Tailwind compiles each dark utility into a prefers-color-scheme media query. The browser decides which branch applies, and your page has no say.
That is fine for simple sites. It fails when you want any of these:
- A visible theme button on the page.
- A saved choice that differs from the system setting, such as a user on a dark OS who prefers your site in light.
- A "system" option alongside "light" and "dark".
A media query cannot be switched from JavaScript. You cannot add or remove it from the page. So you need a condition that your own code can control. The common choices are a class on an ancestor element, or an attribute such as data-theme.
What changes in the generated CSS
Take this utility: dark:bg-gray-900.
With the default strategy, Tailwind emits roughly this:
@media (prefers-color-scheme: dark) {
.dark\:bg-gray-900 {
background-color: #111827;
}
}With the class strategy, it emits a rule that depends on an ancestor:
.dark .dark\:bg-gray-900 {
background-color: #111827;
}Your HTML does not change. You still write dark:bg-gray-900. Only the condition behind the variant changes. Now the rule applies when some ancestor, usually <html>, carries the dark class. Your JavaScript can add and remove that class at any time.
The exact selector Tailwind generates differs between versions. Do not depend on its shape. Depend on the behavior: a dark utility applies when the marker is on an ancestor.
Configuring the strategy in Tailwind v3
In v3, set the darkMode option in tailwind.config.js.
// tailwind.config.js (Tailwind v3.4.1 and later)
module.exports = {
darkMode: 'selector', // use 'class' in earlier v3 versions
content: ['./src/**/*.{html,js}'],
};The accepted values matter:
| Value | Behavior |
|---|---|
| `'media'` (default) | Uses `prefers-color-scheme`. No page code can override it. |
| `'selector'` | Applies `dark:` when the `.dark` class is on an ancestor. Added in v3.4.1. |
| `'class'` | The same idea in older v3 releases. In 3.4.1 and later, prefer `'selector'`. |
If you are on a v3 release earlier than 3.4.1, use 'class'. Check your installed version before choosing, because an unsupported value will not behave as you expect.
Configuring the strategy in Tailwind v4
Tailwind v4 has no darkMode option. Configuration moved into CSS. You redefine the dark variant yourself with @custom-variant.
/* Tailwind v4 */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));Read the selector in two parts:
.darkmatches an element that has the class itself..dark *matches any descendant of such an element.
The & stands for the element being styled. So the variant means: apply when this element is .dark or is inside one. Including the element itself matters. If you put the class on <html> and style <html> with dark:bg-black, the rule must still match.
The :where() wrapper gives the selector zero specificity. That keeps dark: utilities from beating other utilities by accident. Without it, a dark rule could win over a more specific rule that you expected to win.
Using an attribute instead of a class
You are not limited to a class. Many projects already use a data-theme attribute, set by a design system or a component library. Use the same technique with an attribute selector.
/* Tailwind v4, using a data attribute instead of a class */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));Now <html data-theme="dark"> turns dark styles on. Any other value, or no attribute, leaves them off.
In v3, darkMode also accepts an array form that lets you name your own selector, for example darkMode: ['selector', '[data-theme="dark"]']. Treat that as a v3.4.1-and-later feature too. The array form is not used in v4.
Which marker should you choose?
| Marker | Good fit | Watch out for |
|---|---|---|
| `.dark` class | New projects, and the convention most Tailwind examples use. | Another library may already use a `dark` class for its own purpose. |
| `data-theme` attribute | Projects that already use it. One attribute holds one value, so the state cannot be contradictory. | Your toggle code must set the attribute, not a class. |
The class has one quirk. Nothing stops an element from having both light and dark classes, which is an invalid state. An attribute can only hold one value at a time.
Where to put the marker
Put the marker on <html> in almost every case. Reasons:
- It is an ancestor of everything, including
<body>, sodark:works on any element. - Scripts in
<head>can reach it withdocument.documentElementbefore<body>exists. This matters later, when you prevent a flash of the wrong theme. - It matches what most tutorials, snippets and component libraries assume.
You can put the marker on a smaller element to theme one region. A dark sidebar on a light page is an example. Descendants of that element see dark styles and the rest of the page does not. Remember the self-match rule: in v4 your selector must include the element itself, which the examples above do.
Nesting works in your favor here. Because the rule matches any ancestor with the marker, an inner area can be dark even when the outer page is light. The reverse does not work with this simple selector. A light region inside a dark page still matches .dark *, so dark: styles still apply there. To make a light island inside a dark page, you need extra rules, and that is outside this chapter.
A complete minimal example
This page uses the v4 setup above. The class is hard-coded to show the effect. No JavaScript is involved yet.
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/styles.css" />
</head>
<body class="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
<h1 class="text-2xl font-bold">Hello</h1>
<p class="text-gray-600 dark:text-gray-300">
This page is dark because the html element has the dark class.
</p>
</body>
</html>Try this:
- Build the CSS with your normal Tailwind command.
- Open the page. It renders dark.
- Delete
class="dark"from<html>and reload. It renders light. - Switch your operating system between light and dark. The page does not react.
Step 4 is the point. The OS setting no longer matters, because nothing in the CSS reads it. The next chapters add a script that sets the marker for you, including a "system" option that reads the OS preference on purpose.
Edge cases and common mistakes
The marker is on the wrong element
If the class is on <body> and you style <html> or <body> with dark: in v3, the rule needs the class on an ancestor. Whether an element can match its own marker depends on the generated selector. Put the marker on <html> and the problem disappears.
Mixing up config styles across versions
A darkMode key in tailwind.config.js does nothing in a v4 project that uses only CSS configuration. In v4, the @custom-variant line is the setting. The reverse is also true: @custom-variant has no effect in v3. If dark classes do nothing after you "configured" them, check which version is installed first.
Typos in the marker
The class name must match exactly. Dark, dark-mode and darkmode do not match .dark. The same goes for attribute values: data-theme="Dark" does not match [data-theme=dark].
Forgetting that `media` is still the default
If you never changed the config, dark: follows the OS. Toggling a class on <html> will then do nothing visible, because the generated CSS is a media query. This is the most common reason a hand-built toggle seems broken.
Stale builds
Tailwind generates CSS from your source. After you change darkMode, restart your dev server or rebuild. A cached stylesheet still contains media-query rules.
Content scanning
Dark utilities are found by scanning your files, like any other class. In v3, make sure your content globs include the files that use dark: classes. A class that is built from string pieces at runtime, such as 'dark:bg-' + color, will not be detected. Write full class names.
Choosing between the two strategies
| Question | Media strategy | Class or selector strategy |
|---|---|---|
| Follows the OS automatically | Yes | Only if your script reads the OS preference |
| Offers a user toggle | No | Yes |
| Needs JavaScript | No | Yes |
| Risk of a flash of the wrong theme | None | Yes, if the script runs late |
| Setup cost | None | One config line plus a script |
Choose the media strategy when you want no code and OS-driven theming is enough. Choose the class or selector strategy when users need to override the system, or when you want a persisted choice. The flash risk is real, and a later chapter shows how to avoid it.
Summary of the working model
dark:is a variant. It wraps a utility in a condition.- The condition is a media query by default, and a selector match on an ancestor under the manual strategy.
- In v3, you set
darkModeto'selector'(3.4.1 and later) or'class'(earlier). - In v4, you redefine the variant with
@custom-variant, using a class or a data attribute. - Put the marker on
<html>unless you want to theme one region. - After a change, rebuild, and confirm the installed version.
Exercise
A teammate switched a v4 project to a manual toggle. The button adds the dark class to <html>, and the class appears in DevTools, but nothing changes visually. The stylesheet has only @import "tailwindcss";. What is wrong, and what one line fixes it?
Show answer
With no custom variant, dark: still compiles to the prefers-color-scheme media query, so the dark class on <html> is ignored. Add @custom-variant dark (&:where(.dark, .dark *)); after the import, then rebuild. The utilities then apply when the element or an ancestor has the dark class.
Exercise
Your design system sets data-theme="dark" on <html>. Write the Tailwind v4 line that makes dark: respond to it, and explain why the selector includes both [data-theme=dark] and [data-theme=dark] *.
Show answer
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));. The first part matches the element that carries the attribute, such as <html> itself. The second part matches all of its descendants. Without the first part, dark: utilities placed on the marked element itself would not apply.