CSS
Tutorial: build your own dark theme with CSS variables
Use CSS custom properties to build a reusable dark theme across your whole page.
Ever changed a color in CSS and had to find-and-replace it in fifteen different places? CSS variables exist exactly so that never happens to you again.
Step 1: declare your variables
:root {
--color-bg: #0b1620;
--color-surface: #101e27;
--color-text: #ffffff;
--color-accent: #00e5bf;
}
:root is like a global vault where you keep your colors. --color-bg is the variable's name (the -- prefix is required).
Step 2: use them in your styles
body {
background-color: var(--color-bg);
color: var(--color-text);
}
.card {
background-color: var(--color-surface);
border: 1px solid var(--color-accent);
}
var(--color-bg) tells CSS "use whatever value is stored in that variable". If you want to change your whole color scheme tomorrow, you only touch the :root block.
Step 3: create an alternate light theme (optional, for the brave)
[data-theme='light'] {
--color-bg: #ffffff;
--color-surface: #f2f2f2;
--color-text: #111111;
}
<body data-theme="light">
By adding data-theme="light" to the <body>, every variable automatically changes value and drags along any style that uses them. This is, essentially, magic disguised as CSS.
What did you just learn?
- How to declare CSS variables with
:rootand--name. - How to use them with
var(--name). - How to swap an entire theme by editing just one place.