How can I define colors as variables in CSS?

CSS supports this natively with CSS Variables.

Example CSS file

:root {
    --main-color:#06c;
}

#foo {
    color: var(--main-color);
}

For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).

Manipulating a CSS variable in JavaScript/client side

document.body.style.setProperty('--main-color',"#6c0")

Support is in all the modern browsers

Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.

Leave a Comment