CSS variables (custom properties). How to declare them, control their scope, and use them for themes, responsive design, and live updates from JavaScript.
What CSS variables are
CSS variables let you store a value once and reuse it across your stylesheet. Unlike preprocessor variables in SASS or LESS, they are native to CSS and can be changed at runtime with JavaScript.
Declaring and using variables
Names start with two dashes (--). You read them with the var() function:
:root {
--main-bg-color: coral;
}
body {
background-color: var(--main-bg-color);
}
--main-bg-color holds coral. Any element can reference it via var(--main-bg-color).
Variable scope
Variables follow normal CSS cascade rules. Define them globally on :root, or locally inside a selector:
.container {
--container-padding: 20px;
padding: var(--container-padding);
}
--container-padding only applies inside .container and its children.
Responsive design
Change variable values inside media queries instead of repeating whole rule sets:
:root {
--font-size: 16px;
}
@media screen and (min-width: 600px) {
:root {
--font-size: 18px;
}
}
body {
font-size: var(--font-size);
}
Font size bumps up once the viewport passes 600px.
Theming
Define a colour palette as variables, then swap them for a dark theme:
:root {
--primary-color: navy;
--secondary-color: skyblue;
}
.theme-dark {
--primary-color: black;
--secondary-color: grey;
}
body {
color: var(--primary-color);
background-color: var(--secondary-color);
}
Adding theme-dark to the body overrides the defaults for every rule that uses those variables.
Updating variables with JavaScript
document.documentElement.style.setProperty('--primary-color', 'green');
One line changes --primary-color everywhere it is referenced.
Reusable components
Variables work well with component-style CSS in React, Angular, or Vue:
.button {
--button-bg-color: blue;
background-color: var(--button-bg-color);
color: white;
padding: 10px 15px;
}
.button-alert {
--button-bg-color: red;
}
.button-alert reuses everything from .button but overrides the background colour.
Why use them
- Maintainability: Change a value once instead of hunting through a large stylesheet.
- Flexibility: Handy for themes and responsive tweaks.
- Live updates: JavaScript can change them without reloading the page.
Best practices
- Naming: Use clear, consistent variable names.
- Global vs local: Put site-wide values on
:root; scope component-specific ones locally. - Fallbacks: Provide a fallback value inside
var()for older browsers.
body {
background-color: var(--main-bg-color, blue); /* Fallback to blue if --main-bg-color is not defined */
}
CSS variables cut down repetition and make global changes straightforward. Start with colours and spacing, then expand from there.

