Sub topic 3
Dark mode, class detection, and reusable Tailwind styles
Assume you know HTML, the CSS box model, selectors, and basic npm or component workflows. Tailwind generates CSS by finding complete utility names in your source files. This affects dark mode, custom themes, and dynamic class names.
Dark mode with the `dark` variant
The dark: prefix applies a utility when dark mode is active. By default, Tailwind can follow the user’s prefers-color-scheme setting.
<article class="bg-white p-6 text-slate-900 dark:bg-slate-900 dark:text-white">
<h2 class="text-xl font-semibold">System-aware card</h2>
<p class="mt-2 text-slate-600 dark:text-slate-300">
This text adapts to the active color scheme.
</p>
</article>For a theme switch controlled by your application, configure the dark variant to use a class such as dark on an ancestor element. Then toggle that class on <html> or another root element.
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));<html class="dark">
<!-- dark: utilities are active inside this element -->
</html>Dynamic class names and class detection
Tailwind scans source text for complete class names. It cannot reliably generate a class assembled at runtime.
// Avoid: the scanner cannot infer every possible result.
const badClass = `text-${color}-600`;
// Prefer: each complete class appears literally in the source.
const textClasses = {
red: "text-red-600",
green: "text-green-600",
};
const goodClass = textClasses[color];The same rule applies to dark:, responsive prefixes, and arbitrary values.
Customizing the theme and design tokens
A design token is a named design value, such as a brand color. In Tailwind CSS v4, define color tokens in the --color-* namespace.
@import "tailwindcss";
@theme {
--color-brand: #4f46e5;
}This creates utilities such as bg-brand, text-brand, and related color variants.
Arbitrary values for one-off styles
Square brackets provide a value outside the configured scale:
<div class="w-[320px] bg-[#1da1f2] p-[13px]">
A deliberately one-off value
</div>Prefer theme tokens for values that repeat. Arbitrary values are useful for measured, isolated exceptions.
Reusing styles with components and `@apply`
Use a component when markup and behavior repeat. In a template system, a reusable component can accept content and variants while keeping utility classes visible.
For a repeated custom class, @apply combines utilities:
.btn-primary {
@apply rounded-lg bg-brand px-4 py-2 font-semibold text-white hover:bg-indigo-700;
}Use @apply selectively. Components usually preserve Tailwind’s composition and variant model better than large collections of custom classes.
Exercise
Why might text-${color}-600 fail, and what is one safe alternative?
Show answer
Tailwind may not detect the assembled class. Use a map whose values contain complete class names, such as text-red-600 and text-green-600.