AdvancedLesson 27 of 306 min read

Dark mode and theming with CSS variables

Add dark mode and multiple themes with colour variables, prefers-color-scheme, a toggle button and a good dark palette.

In this lesson you will

  • Name colours by role
  • Follow the system theme
  • Add a toggle that remembers the choice
  • Design a comfortable dark palette

About 17 minutes

Giving visitors the lights-out option

It is eleven at night. A visitor opens your site on their phone, and a blinding white page lights up the room. They sigh, and some will leave. Others use a phone set to dark mode and expect every site to respect it. Adding dark mode is a lovely way to show care, and with the variables from lesson 24, it is much easier than you might fear. The whole job is: define your colours as variables, then provide a second set of values.

Step 1: colours as variables

:root {
  color-scheme: light dark;

  --bg: #FAF8FF;
  --surface: #FFFFFF;
  --text: #14112E;
  --muted: #5F5B80;
  --border: #E6E1F5;
  --brand: #5A28C8;
}

body { background: var(--bg); color: var(--text); }
.card { background: var(--surface); border: 1px solid var(--border); }

Notice the names: --bg, --surface, --text. They describe what the colour is for, not what it looks like. That is what lets you swap them. A name like --white would be a lie in dark mode.

The line color-scheme: light dark tells the browser that the page supports both. It makes built-in elements, such as scrollbars, form fields and the default page background, switch automatically.

Step 2: the dark set, following the visitor’s system

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0E0C22;
    --surface: #1A1736;
    --text: #F2EFFF;
    --muted: #A9A4D0;
    --border: #2D2A52;
    --brand: #9B7BFF;
  }
}

Everything that uses the variables changes automatically. You do not touch a single component rule. Notice that the brand colour is lighter in dark mode. A deep violet that looks great on white is too dim against a dark background, so adjust it for contrast.

This page already uses variables. Add a prefers-color-scheme: dark media query that redefines –bg, –text and –brand for dark mode. If your own system is set to dark, the result will switch.

<style>
 :root { color-scheme: light dark; --bg:#FAF8FF; --text:#14112E; --brand:#5A28C8; }
 body { background:var(--bg); color:var(--text); font-family:Arial; padding:20px; }
 a, h2 { color:var(--brand); }
 /* dark mode here */
</style>
<h2>Dark mode ready</h2>
<p>This text and the heading use variables. <a href="#">A link</a></p>

@media (prefers-color-scheme: dark) { :root { –bg:#0E0C22; –text:#F2EFFF; –brand:#9B7BFF; } }

<style>
 :root { color-scheme: light dark; --bg:#FAF8FF; --text:#14112E; --brand:#5A28C8; }
 body { background:var(--bg); color:var(--text); font-family:Arial; padding:20px; }
 a, h2 { color:var(--brand); }
 @media (prefers-color-scheme: dark) { :root { --bg:#0E0C22; --text:#F2EFFF; --brand:#9B7BFF; } }
</style>
<h2>Dark mode ready</h2>
<p>This text and the heading use variables. <a href="#">A link</a></p>

Step 3: a toggle button

Following the system is a great default, but people also like a switch. A common pattern stores the choice in an attribute on the page and in the browser’s storage.

:root { /* light values */ }
:root[data-theme="dark"] {
  --bg: #0E0C22;
  --surface: #1A1736;
  --text: #F2EFFF;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #0E0C22;
    --surface: #1A1736;
    --text: #F2EFFF;
  }
}
<button id="theme" aria-pressed="false">Dark mode</button>
<script>
  const root = document.documentElement;
  const btn = document.getElementById('theme');
  const saved = localStorage.getItem('theme');
  if (saved) root.dataset.theme = saved;
  btn.addEventListener('click', () => {
    const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
    root.dataset.theme = next;
    btn.setAttribute('aria-pressed', String(next === 'dark'));
    localStorage.setItem('theme', next);
  });
</script>

The logic reads like a short story: use the saved choice if there is one, otherwise follow the system. The CSS selectors above give the explicit choice priority. Put the first few lines of the script early in the head to avoid a flash of the wrong theme when the page loads.

Click the button to toggle the theme using a data-theme attribute. Then add a third value for a cosy warm theme called sepia.

<style>
 :root { --bg:#FAF8FF; --text:#14112E; }
 :root[data-theme="dark"] { --bg:#0E0C22; --text:#F2EFFF; }
 body { background:var(--bg); color:var(--text); font-family:Arial; padding:20px; transition: background .3s, color .3s; }
 button { padding:10px 18px; border-radius:999px; border:0; background:#5A28C8; color:#fff; font-weight:700; }
</style>
<p>Toggle the theme:</p>
<button id="t">Switch</button>
<script>
 document.getElementById('t').onclick = function(){
  var r = document.documentElement;
  r.dataset.theme = r.dataset.theme === 'dark' ? 'light' : 'dark';
 };
</script>

Add :root[data-theme=”sepia”] { –bg:#F6ECD9; –text:#3B2F1B; } and cycle through three values in the script.

<style>
 :root { --bg:#FAF8FF; --text:#14112E; }
 :root[data-theme="dark"] { --bg:#0E0C22; --text:#F2EFFF; }
 :root[data-theme="sepia"] { --bg:#F6ECD9; --text:#3B2F1B; }
 body { background:var(--bg); color:var(--text); font-family:Arial; padding:20px; transition: background .3s, color .3s; }
 button { padding:10px 18px; border-radius:999px; border:0; background:#5A28C8; color:#fff; font-weight:700; }
</style>
<p>Toggle the theme:</p>
<button id="t">Switch</button>
<script>
 var order = ['light','dark','sepia'];
 document.getElementById('t').onclick = function(){
  var r = document.documentElement;
  var i = order.indexOf(r.dataset.theme || 'light');
  r.dataset.theme = order[(i + 1) % order.length];
 };
</script>

Designing a good dark palette

  • Avoid pure black. A very dark blue or grey, such as #0E0C22, is easier on the eyes and lets shadows and layers show.
  • Avoid pure white text. Slightly off-white reduces glare.
  • Lift surfaces by lightening them. In dark mode, a card sits lighter than the page behind it. Shadows barely show on dark colours, so lightness communicates height.
  • Desaturate and lighten your brand colour so it keeps contrast without vibrating.
  • Check contrast again. The 4.5 to 1 target applies in dark mode too.
  • Treat images. Bright photos can glare on dark pages. A touch of filter: brightness(.9) in dark mode, and transparent PNG logos with dark text, may need an alternate version.

Theming beyond dark mode

The system you just built is a theming system. A second set of variable values can also be a seasonal theme, a high-contrast mode, a client’s brand colours on a white-label product, or a section of a page that deserves a different feel. The CSS never changes, only the values do. This is the real power of the design tokens you met in lesson 24.

.theme-promo {
  --bg: linear-gradient(135deg, #6C2BE0, #4A6EDD);
  --text: #fff;
  --brand: #fff;
}
.section { background: var(--bg); color: var(--text); }
Common mistake

Using hard-coded colours inside components, such as background: #fff, in a site that has dark mode. That component will glow white on a dark page. Search your stylesheet for raw colour values and replace them with variables.

Test both themes

Switch your system to dark mode, or use the emulation option in browser developer tools (Rendering panel, Emulate prefers-color-scheme), and walk through every page. Check text, borders, forms, images and focus rings.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does color-scheme: light dark do?

  1. Adds a toggle
  2. Tells the browser the page supports both and adapts built-in elements
  3. Sets the font
  4. Hides images

It lets browser-drawn UI follow the theme.

Why name variables by role, such as --surface?

  1. It is shorter
  2. The role stays true when the colour changes
  3. It is required
  4. It adds contrast

A colour name would be wrong in the other theme.

Which media query follows the visitor’s system theme?

  1. prefers-color-scheme
  2. theme-mode
  3. dark-only
  4. color-mode

It reads the system setting.

Which is a good dark mode practice?

  1. Pure black background with pure white text
  2. A very dark tinted background and slightly off-white text
  3. Neon colours
  4. Removing borders

Softer extremes are more comfortable.

Where can you store a visitor’s theme choice?

  1. localStorage
  2. A CSS file
  3. An image
  4. The title tag

localStorage remembers it on that device.

Summary

  • Define colours as role-named variables.
  • Redefine the variables inside prefers-color-scheme: dark.
  • A data-theme attribute lets visitors choose.
  • Test contrast and images in both themes.

Next lesson

Next: organising CSS so a big stylesheet stays readable, with naming systems and cascade layers.

Questions

Do I need JavaScript for dark mode?

No for following the system. You need a little for a toggle that remembers a choice.

How do I avoid a flash of the wrong theme?

Set the theme attribute with a tiny script in the head, before the page renders.

Should my logo change in dark mode?

If it has dark text, yes. Provide a light version or use an SVG that uses currentColor.

Progress is saved in this browser.