跪拜 Guibai
← Back to the summary

One theme.css to Rule Every Color: Three Token Layers Collapse 84 Hardcoded Hex Values into a Single data-theme Override

Core conclusion: A unified theme.css is not "a file for storing colors" but the only place in the entire project where color value literals may appear. It uses CSS Custom Properties to build a three-layer token structure — "primitive value → semantic value → component value" (Design Tokens) — and components only reference the semantic layer. Theme switching then becomes a single data-theme attribute change: 84 hardcoded colors across 12 components collapse into 1 definition and 0 component changes.


Table of Contents


1. Verdict first: global styles need a single source of truth

Here is the criterion up front: if your project fits "one structure, many visual outputs" — brand recolors, light/dark themes, multi-tenant white labeling — then colors should not be scattered across components. They belong in one theme.css.

Its responsibility boundary is narrow, exactly two rules:

As an analogy 🎭: theme.css is like the main breaker in your house. You don't need to go room by room changing bulb wattage; adjust the voltage once at the main panel and all the lights change together. If each room wired its own cable and set its own voltage, that's not renovation, that's an accident scene.

What does this consolidation save? Do the math. Say a medium project has 12 component files, each averaging 7 hardcoded colors (background, text, border, hover, disabled state each count as one). That's $12 \times 7 = 84$ color values across the project. These 84 places are exactly "where you must go when the brand color changes."

2. Why scattered colors inevitably spiral out of control (Cost of Hardcoding)

Hardcoding isn't "fast to write"; it's "postponing the cost to the first recolor." It has three fixed costs:

A rule worth remembering: the third time the same hex value is handwritten into the project, it has already become the de facto standard — except that standard lives in three files and nobody knows who's in charge.

Sass variables are often proposed as the cure, but they have a fatal limitation: variables are replaced at compile time, so they are constants. By the time the user clicks "dark mode", compilation is long finished; constants don't change. This is exactly the watershed between CSS Custom Properties and preprocessor variables.

References:

3. theme.css's three-layer token structure (Token Layers)

A theme.css that survives long-term is always split into three layers internally, not a flat pile of variables:

Layer What names look like What it describes Who may reference it
One: Primitive --gray-900, --brand-500 The color itself, carrying no purpose Only the semantic layer
Two: Semantic --text-primary, --bg-card A purpose, pointing at a primitive Component styles
Three: Component --button-bg, --card-radius A per-component knob Only inside that component

There is one rule and it must hold: component code may only reference layers two and three, and may never reference layer one directly. Because once a component writes var(--gray-900), when the dark theme overrides --text-primary, this component becomes the one that got away.

Why force three layers? Because a dark theme changes "purpose," not "color." Under dark mode the body text should turn lighter, but the semantic meaning "body text" hasn't changed. So as long as the dark theme overrides only layer two, every component referencing layer two changes automatically — this is the source of every capability in the next section.

One realistic warning ⚠️: don't overuse layer three. If every component defines its own set of color variables, theme.css becomes a giant configuration file again, just out of control in a new place.

4. A runnable theme.css and page (Runnable Template)

Put these two files in the same directory and double-click index.html to see the switching in action. No build, no dependencies.

First, theme.css:

/* theme.css —— the only file in the project where color literals may appear */
:root {
  /* Layer one: primitives, only describe colors, no purpose */
  --gray-0: #ffffff;
  --gray-50: #f7f8fa;
  --gray-900: #14171f;
  --brand-500: #2563eb;
  --button-radius: 10px;

  /* Layer two: semantic values, only describe purpose, pointing at primitives */
  --bg-page: var(--gray-50);
  --bg-card: var(--gray-0);
  --text-primary: var(--gray-900);
  --accent: var(--brand-500);
  --space-2: 8px;
  --space-4: 16px;

  /* Layer three: component values, only describe one component, pointing at semantic values */
  --button-bg: var(--accent);
  --button-text: var(--gray-0);
}

/* Dark theme overrides only the semantic layer; component layer follows automatically; component files untouched */
[data-theme="dark"] {
  --bg-page: #0f1117;
  --bg-card: #171a22;
  --text-primary: #e6e8ee;
  --accent: #60a5fa;
}

Second, index.html:

<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
  <meta charset="utf-8" />
  <title>theme.css minimum example</title>
  <link rel="stylesheet" href="theme.css" />
  <style>
    body {
      margin: 0;
      padding: 32px;
      background: var(--bg-page);
      color: var(--text-primary);
      font-family: system-ui, sans-serif;
    }
    .card {
      background: var(--bg-card);
      border-radius: 12px;
      padding: var(--space-4);
    }
    .btn {
      background: var(--button-bg);
      color: var(--button-text);
      border: 0;
      border-radius: var(--button-radius);
      padding: var(--space-2) var(--space-4);
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="card">
    <h1>统一主题</h1>
    <p>组件的样式里没有出现任何色值。</p>
    <button class="btn" id="toggle">切换主题</button>
  </div>
  <script>
    // Read the last choice on page load to avoid jumping back to light after refresh
    const root = document.documentElement;
    const savedTheme = localStorage.getItem("theme");
    if (savedTheme) root.dataset.theme = savedTheme;

    // The click changes one attribute; every component referencing semantic variables redraws automatically
    document.getElementById("toggle").addEventListener("click", () => {
      const nextTheme = root.dataset.theme === "dark" ? "light" : "dark";
      root.dataset.theme = nextTheme;
      localStorage.setItem("theme", nextTheme);
    });
  </script>
</body>
</html>

Note that .card and .btn don't contain a single hex color — they only know semantic names like var(--bg-card). That is what "components neither know nor care about the theme" looks like concretely.

5. Theme switching: change one attribute, zero component changes (Theme Switching)

All the mechanics were laid down above; this section spells them out. Switching works through three things in concert:

Compare the costs: with hardcoding, a dark theme means going back to 84 color values and judging each one; with tokens, you add one [data-theme="dark"] block with 4 semantic variables. The former is editing code; the latter is adding configuration.

One easily missed coupling: theme.css is tightly tied to style loading order. Variable definitions must come before the component styles that use them, otherwise var() resolves to empty and elements become transparent. Vite splits CSS per module by default, so in production component styles can be injected before the theme file — that pitfall is covered in detail in Disabling CSS code splitting in Vite — and the takeaway is that the theme file must be imported first at the entry point.

6. First-screen flash and system preference (FOUC & prefers-color-scheme)

The variable approach has one side effect of its own: first-screen flash (Flash of Unstyled Content). The browser paints the page in the default light theme first, the script reads localStorage and switches to dark afterward, and the user sees a white flash for one frame.

The fix is to move theme reading before render, in <head>, after the stylesheets, before <body>:

<script>
  // Runs synchronously, before the first paint, avoiding the white flash
  const storedTheme = localStorage.getItem("theme");
  const systemDark = matchMedia("(prefers-color-scheme: dark)").matches;
  document.documentElement.dataset.theme = storedTheme || (systemDark ? "dark" : "light");
</script>

Two standard capabilities appear here, each worth a note:

References:

7. Symptom → cause → solution look-up table (Symptom Table)

Symptom Cause Fix
Some spots stay the old color after a brand recolor Component hardcoded a hex value instead of using variables Search the whole project for hex values, replace each with a semantic variable, add a lint rule
One card stays white in dark mode That component referenced the primitive --gray-0 directly, bypassing the semantic layer Components may only reference var(--bg-card); annotate the primitive layer to forbid external references
The whole page flashes white when switching themes The script reading localStorage runs at the end of <body> Move the synchronous theme-reading script into <head>, before first paint
Scrollbar and inputs stay light on a dark page Only color variables changed; color-scheme was never declared Add color-scheme: light dark to :root
Theme variables are defined but components render transparent Component styles were injected before theme.css, so var() resolves empty Import the theme file first at the entry point; disable CSS code splitting if necessary
A local dark area drags the whole page dark Variables defined on :root give too wide a scope Hang the override block on the local container's data-theme, use inheritance for local theming

8. Five ways to break theme.css (Pitfalls)

  1. Writing literals back into the semantic layer: --text-primary: #14171f written dead, not pointing at var(--gray-900). This one color has no single point of definition and gets skipped when gray scales change.
  2. Naming by color and using it as semantics: a component writes background: var(--blue-500). The day blue becomes purple, the variable name becomes a lie.
  3. Only two themes, no transition: large color blocks snap abruptly; it looks bad. A body level transition: background-color .2s, color .2s helps, but don't add a wildcard transition to all elements — it slows scrolling.
  4. Using !important to win back styles: a component style loses, so !important overrides the token. That's declaring "I'm not part of the theme system," and it becomes a permanent exception in dark mode.
  5. All variables piled into :root, ungrouped: 300 lines with no comments and no sections; newcomers don't dare change or delete, so they keep hardcoding. Separating into "primitive / semantic / component" sections with comments is the cheapest governance.

9. When NOT to use a global theme.css (When Not to Use)

This approach isn't unconditional. In three situations, forcing it adds maintenance cost:

The criterion is plain: the variable system solves "one structure, multiple visual outputs." When there is only one visual, its benefit approaches zero and only the cost remains.

10. The verdict: use it or not (Verdict)

Use it: the project needs any of light/dark themes, brand recolor, or multi-tenant white labeling; or component count exceeds 20, or the third hand-written duplicate of a color appears. Then theme.css returns "one value changed, whole site updated" at the cost of one file and one lint rule.

Don't use it: single-page static sites, internal tools with no theming needs, or micro-frontends with isolated styles and no shared build. In these, write the business logic first; extract tokens once colors actually start repeating.

One self-check, finally: search the project for hex color occurrences. If dozens appear beyond theme.css, you already have a theme.css — it just isn't being treated as the single source yet.


This structure's value lies not in the file itself but in one criterion: when the answer to "how many files does one color change touch" is 1, theming stops being a burden. If the answer is still a dozen, don't rush to add variables; first clean up the scattered color values.

This column, Full Stack Development, covers frontend engineering, style architecture, full-chain feature implementation, and backend collaboration. Each piece includes runnable code and a symptom/solution table, continuously updated. Subscribe on the column page to read the frontend track in order.