Skip to the main content

All tutorials

Dark mode with CSS variables and a switch

  • Level: Intermediate
  • About 5 minutes to read (an estimate from the word count: 852 words at 200 words a minute)
  • Last checked:

Put colours in custom properties, follow the system's dark setting, and add a switch that overrides it.

What you will be able to do

  • Declare colours once as custom properties on a component
  • Follow the system with prefers-color-scheme by changing values only
  • Override the system with a data-theme attribute and a switch button
  • Keep the choice in localStorage, with a fallback when storage is blocked
  • Explain why the script is a file and not an inline block

Tokens as custom properties

A dark theme is a second set of colours. Keep the colours where you can change them in one place: custom properties. A custom property is a name that starts with two hyphens, such as --surface. You set it on an element and read it with var(--surface). Child elements inherit it.

Name the properties for their job, not their colour. --text and --surface stay true in both themes, but --white would not. These names are called design tokens, and the card in the first example uses five of them.

.card {
  --surface: #ffffff;
  --text: #1b1f2a;
  color: var(--text);
  background: var(--surface);
}
Values are declared once. Every rule after this one uses the names.

HTML

<article class="tok-card" aria-labelledby="tok-card-title">
  <h2 class="tok-card__title" id="tok-card-title">Colours in tokens</h2>
  <p>Every colour in this card comes from a custom property declared once on the card.</p>
  <p><a class="tok-card__link" href="#tok-card-title">A link that uses the accent token</a></p>
</article>

CSS

/* Tokens: names for decisions. They are declared once, on the component's own class. */
.tok-card {
  --tok-surface: #ffffff;
  --tok-text: #1b1f2a;
  --tok-muted: #4a5163;
  --tok-border: #c9ced9;
  --tok-accent: #3730a3;
  max-width: 28rem;
  padding: 1.25rem;
  color: var(--tok-text);
  background: var(--tok-surface);
  border: 1px solid var(--tok-border);
  border-radius: 10px;
}
.tok-card__title { margin: 0 0 0.5rem; font-size: 1.25rem; }
.tok-card p { margin: 0 0 0.75rem; color: var(--tok-muted); }
.tok-card__link { color: var(--tok-accent); }
.tok-card__link:focus-visible {
  outline: 3px solid var(--tok-accent);
  outline-offset: 2px;
}

prefers-color-scheme

The operating system and the browser can tell a page whether the visitor prefers a light or a dark scheme. Your CSS reads this with the media feature prefers-color-scheme. In the media query, change the values of the tokens and nothing else. No other rule in the style sheet needs to know about the dark theme.

Add color-scheme: light dark to the same element. It tells the browser that the element can be shown in both schemes. The browser then uses a fitting default for form controls, scrollbars and the page canvas. Without it, a dark card may still contain a light text field.

Check contrast in both themes. A colour that passes against a white surface can fail against a dark one. The checks for this page measure text contrast in the light and the dark scheme.

HTML

<article class="dark-card" aria-labelledby="dark-card-title">
  <h2 class="dark-card__title" id="dark-card-title">Follows your system</h2>
  <p>Switch your device or browser between light and dark. This card changes with it, because only the token values change.</p>
  <p><a class="dark-card__link" href="#dark-card-title">A link that uses the accent token</a></p>
</article>

CSS

.dark-card {
  color-scheme: light dark;   /* tells the browser the card supports both, so form controls and scrollbars follow */
  --dc-surface: #ffffff;
  --dc-text: #1b1f2a;
  --dc-muted: #4a5163;
  --dc-border: #c9ced9;
  --dc-accent: #3730a3;
  max-width: 28rem;
  padding: 1.25rem;
  color: var(--dc-text);
  background: var(--dc-surface);
  border: 1px solid var(--dc-border);
  border-radius: 10px;
}
/* Only the values change. No rule below touches a colour directly. */
@media (prefers-color-scheme: dark) {
  .dark-card {
    --dc-surface: #1d2130;
    --dc-text: #eceef5;
    --dc-muted: #b6bccb;
    --dc-border: #444b5c;
    --dc-accent: #b4b8ff;
  }
}
.dark-card__title { margin: 0 0 0.5rem; font-size: 1.25rem; }
.dark-card p { margin: 0 0 0.75rem; color: var(--dc-muted); }
.dark-card__link { color: var(--dc-accent); }
.dark-card__link:focus-visible {
  outline: 3px solid var(--dc-accent);
  outline-offset: 2px;
}

A data-theme override

Some visitors want a different theme from their system's setting. For them, add an attribute on the element, for example data-theme="dark", and write a second set of values that uses it. The attribute is a convention and not a standard: any name works as long as the CSS and the script agree.

Write the rules in an order that makes the override win. First the media query, limited to the cases where no light choice was made: :not([data-theme="light"]). Then the explicit [data-theme="dark"] block. A visitor who chose light on a dark system gets light, and a visitor who has made no choice gets the system's setting.

A switch button

The control is a button that reports its state with aria-pressed. Its label does not change, because the pressed state already says whether dark is on. A label that flipped between "Dark theme" and "Light theme" would be read as the opposite of the state.

When the page opens, the script reads the system's setting with matchMedia so that the button starts in the right state. On a click, it flips data-theme and aria-pressed together.

Remembering the choice

To keep the choice for the next visit, store it with localStorage. It keeps a small piece of text for your site until it is cleared. Storage can be unavailable, for example in a private window or in a sandboxed frame, and then the call throws an error. Put every use inside try and catch, and decide what the page does when storing fails.

function remember(theme) {
  try {
    localStorage.setItem('theme', theme);
    return true;
  } catch (error) {
    return false;
  }
}
The function says whether it worked, so the page can tell the visitor the truth.

The preview on this page is a sandboxed frame and cannot store anything. So the example shows the fallback: the switch works, and a line of text says that the choice lasts until you reload. To see the choice kept, use the Playground to download the example as a ZIP and serve it from your own site. In an ordinary page the same script keeps the choice across a reload. The checks for this tutorial confirm both behaviours in Chrome.

HTML

<div class="theme-demo" id="theme-demo-root">
  <article class="theme-demo__card" aria-labelledby="theme-demo-title">
    <h2 class="theme-demo__title" id="theme-demo-title">A switch that overrides the system</h2>
    <p>The button sets <code>data-theme</code> on this example. With no choice made, the system setting decides.</p>
    <p>
      <button type="button" class="theme-demo__button" id="theme-demo-button" aria-pressed="false">Dark theme</button>
    </p>
    <p class="theme-demo__status" id="theme-demo-status" role="status"></p>
  </article>
</div>

CSS

.theme-demo {
  color-scheme: light;
  --td-surface: #ffffff;
  --td-text: #1b1f2a;
  --td-muted: #4a5163;
  --td-border: #c9ced9;
  --td-accent: #3730a3;
  --td-on-accent: #ffffff;
  min-height: 100vh;
  padding: 1rem;
  color: var(--td-text);
  background: var(--td-surface);
}
/* 1. No choice made: follow the system. */
@media (prefers-color-scheme: dark) {
  .theme-demo:not([data-theme="light"]) {
    color-scheme: dark;
    --td-surface: #12141c;
    --td-text: #eceef5;
    --td-muted: #b6bccb;
    --td-border: #444b5c;
    --td-accent: #b4b8ff;
    --td-on-accent: #12141c;
  }
}
/* 2. A choice made with the switch wins over the system. */
.theme-demo[data-theme="dark"] {
  color-scheme: dark;
  --td-surface: #12141c;
  --td-text: #eceef5;
  --td-muted: #b6bccb;
  --td-border: #444b5c;
  --td-accent: #b4b8ff;
  --td-on-accent: #12141c;
}
.theme-demo__card {
  max-width: 30rem;
  padding: 1.25rem;
  border: 1px solid var(--td-border);
  border-radius: 10px;
}
.theme-demo__title { margin: 0 0 0.5rem; font-size: 1.25rem; }
.theme-demo__card p { margin: 0 0 0.75rem; }
.theme-demo__status { min-height: 1.5em; color: var(--td-muted); }
.theme-demo__button {
  min-height: 44px;
  padding: 0.5rem 1.25rem;
  font: inherit;
  color: var(--td-accent);
  background: transparent;
  border: 2px solid var(--td-accent);
  border-radius: 8px;
  cursor: pointer;
}
.theme-demo__button[aria-pressed="true"] { color: var(--td-on-accent); background: var(--td-accent); }
.theme-demo__button:focus-visible {
  outline: 3px solid var(--td-text);
  outline-offset: 2px;
}

JavaScript

var root = document.getElementById('theme-demo-root');
var button = document.getElementById('theme-demo-button');
var note = document.getElementById('theme-demo-status');
var KEY = 'hcj-example-theme';

function apply(theme) {
  root.setAttribute('data-theme', theme);
  button.setAttribute('aria-pressed', String(theme === 'dark'));
}

// Storage can be blocked (a sandboxed preview, a private window), so every use sits in try/catch.
function remember(theme) {
  try {
    localStorage.setItem(KEY, theme);
    return true;
  } catch (error) {
    return false;
  }
}

function recall() {
  try {
    return localStorage.getItem(KEY);
  } catch (error) {
    return null;
  }
}

var saved = recall();
var startDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
apply(saved === 'dark' || saved === 'light' ? saved : (startDark ? 'dark' : 'light'));

button.addEventListener('click', function () {
  var next = button.getAttribute('aria-pressed') === 'true' ? 'light' : 'dark';
  apply(next);
  note.textContent = remember(next)
    ? 'Your choice is kept in this browser.'
    : 'This preview cannot store your choice, so it lasts until you reload.';
});

Why the script is a file

A common tip is to put a small script inline in the head that sets the theme before the page paints. A strict Content Security Policy (CSP) blocks inline scripts, and that is the policy these examples run under. So the script is a file, loaded with <script src>. A file in the head that is loaded without defer runs before the parser reaches the body, and the parser waits for it. A deferred file does not make the parser wait, and a visitor whose saved choice differs from their system setting may see the other theme for a moment. Which trade-off is right depends on your page, and this tutorial has not measured either.

The CSS-first design keeps the problem small. A visitor who has made no choice never needs the script to get the right theme, because the media query handles that case.

All examples on this page passed their checks in Chrome 143 on 3 December 2026. They were not tested in other browsers.

References

These snippets in the gallery use the same techniques: