• CSS custom properties and variables

Having used SASS or LESS one might figure the CSS custom properties and variables to be the equivalent of features available in those preprocessors, but there are a few key differences worth looking into.

First the basics:

// you can set and use custom properties like such: :root {

--foo: #000;

}

button {

background-color: var(--foo); //background is black

}

They’re also inheritable, so if you reassign a local variable it’ll have an effect on all children elements and contrary to preprocessors the browser will actually recalculate all variables and expressions where applicable when that happens.

Fallbacks can be used with commas, you can stack multiple fallbacks after comma, even other variables:

.foo {

color: var(—-my-var, 'blue');

}

This leads us to the main difference from preprocessors: CSS variables are aware of the DOM’s structure and are dynamic.

::root {

--default-color: #000000;

} header {

--primary-color: #ff0000;

}

a {

color: var(--primary-color, --default-color);

} <a href="">this is black</a>

<header>

<a href="">this is red.</a>

</header>

Contrary to the first example of inheritability, this example relies on fallback being aware if the custom property was set in the parent DOM element or not.

Furthermore, they can also be easily changed using javascript:

// get variable from inline style

element.style.getPropertyValue("—-my-var"); // set variable on inline style

element.style.setProperty("--my-var", jsVar + 4);

Supported upward since Edge15.