Changing CSS variables with JavaScript

clock 2 min. read

CSS variables are also called “CSS custom properties” or “cascading variables”. When it was first introduced, preprocessors like Sass or Less had already become the standard in web development. Preprocessors give us a lot of features that don’t supported by native CSS, such as variables, mixins, modules, and so on. These features allow to avoid repetitive styles (DRY) and create more readable CSS structure.

So what is the difference between CSS variables and preprocessor variables then? The main advantage of using native CSS variables is their ability to change dynamically. We can read and change them with JavaScript at runtime. Let’s see how it works.

Declaration and basic usage

Declaring a CSS variable:

:root {
    --primary-color: red;

Using a CSS variable:

element {
    color: var(--primary-color);

We can also declare a variable with a fallback value. If given variable is not defined, the fallback will be used:

element {
    color: var(--primary-color, red);

Interacting with CSS variables from JavaScript

We can interact with CSS variables, reading and changing them using getPropertyValue() and setProperty() JavaScript methods:

// Get a variable
    .getPropertyValue('--primary-color'); // red
// Set a new variable value
    .setProperty('--primary-color', 'blue');

A real-life example. Creating a tooltip with CSS variables

In this example, I wanted to show CSS variables in action. I’ve created a basic tooltip that appears in the list of items. Tooltip is hidden by default. To handle its appearance, I modify three CSS variables using JavaScript: --tooltip-opacity, --tooltip-top and --tooltip-left.

See the Pen abOmjbr by Anastasia (@anreut) on CodePen.


Using CSS custom properties (variables)