Class-Based Dark Mode
Part of the Fundamentals section of Coddy's Tailwind CSS journey. Lesson 49 of 55.
By default, Tailwind dark variants follow the system color preference. To select dark mode with a class, define @custom-variant dark (&:where(.dark, .dark *)); in the stylesheet. A dark utility then applies to the dark-marked element and its descendants.
<div class="dark">
<p class="opacity-100 dark:opacity-50">Museum sample</p>
</div>For example, a descendant with opacity-100 dark:opacity-50 becomes half opaque under a dark ancestor. A real color scheme should change foreground and background together; the opacity example isolates how the selector condition works. A supplied control can toggle the ancestor class without any learner-authored JavaScript.
Challenge
MediumKeep the reading panel at 75 percent opacity in light mode and 30 percent in class-selected dark mode. Use the supplied Theme button to toggle the ancestor class; do not edit its locked JavaScript.
Keep the supplied content and element IDs. Edit the HTML utility classes or the requested CSS. Click Run preview to refresh the preview after edits, then use Check/Run code to grade your work.
Try it yourself
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Practice studio</title><link rel="stylesheet" href="./styles.css"></head><body>
<button id="toggle">Theme</button>
<div data-theme-root><div id="target" class="">Reading panel</div></div>
<script src="./controls.js"></script>
</body></html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
1Meet Tailwind
A Styled First RunChoosing UtilitiesCombining UtilitiesThe Local StylesheetRecap: Meet Tailwind7Sizing and Overflow
Element WidthElement HeightMaximum WidthOverflow BehaviorRecap: Sizing and Overflow10Theme and Dark Mode
Theme Color TokensTheme Spacing TokensTheme Radius TokensClass-Based Dark ModeRecap: Theme and Dark Mode