appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Custom properties and themes

Lesson 2 of 411 minIntermediate

CSS variables, dark mode and a design system in a handful of lines.

Custom properties (CSS variables) store a value you reuse. Define them on :root and read them with var().

:root {
  --ink: #17141f;
  --paper: #fbf7ee;
  --accent: #facc15;
  --space: 1rem;
}
.card {
  color: var(--ink);
  background: var(--paper);
  padding: var(--space);
  border: 2px solid var(--ink);
}
  • They cascade and inherit, so you can override them on any element: .warning { --accent: #ef4444; }.
  • var(--x, fallback) gives a fallback if the variable is missing.
  • Unlike Sass variables, they can change at run time with JavaScript: el.style.setProperty("--accent", "#0ea5e9").

Dark mode

:root { color-scheme: light dark; --bg: #fff; --fg: #111; }
@media (prefers-color-scheme: dark) {
  :root { --bg: #111; --fg: #eee; }
}
body { background: var(--bg); color: var(--fg); }

color-scheme tells the browser that the page supports both, so form controls and scrollbars adapt too. prefers-color-scheme follows the system setting. To let users choose, set a data-theme attribute on <html> and write [data-theme="dark"] { ... }.

Check contrast in both themes

Text must keep a contrast ratio of at least 4.5 to 1 against its background in every theme.

CarefulBrowser extensions and "force dark" modes can change your colors. Declare color-scheme and test with them off, so you see what you designed.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. How do you read a custom property?
2. What advantage do CSS variables have over preprocessor variables?
3. What does color-scheme: light dark tell the browser?