CSS Variables (aka CSS Custom Properties)

Variables serve a useful purpose in programming. They allow a programmer to define a value or piece of functionality in one place, and then easily re-use it elsewhere in the program. If the program needs to change, that change can then be made in one place instead of many. They also allow code to take in and respond to input supplied by another source.

Another benefit of variables is encapsulating complex programming code in simple English.

CSS variables serve the same purpose. For example, it's much easier to remember --primary-color, than to remember #f098CA. It's also much less error prone.

While SASS has variables too, its variables are converted when it's compiled to CSS. In contrast, CSS variables are part of the code rendered by the browser, so it can me modified with Javascript at any time.

Suppose that you want the primary color of your site to be the nice purple #4248f4. Since you will be using the color often, it make sense to store it in a variable.

A variable is declared just like any other CSS property, except that you place two dashes in front of it like so:

--color-primary: #4248f4;

You can re-use the variable anywhere in your site in the following manner:


For example, suppose you want to set text to the primary color, you would do it like so:

color: var(--color-primary);

You can also nest variables.

For example, suppose you won't to add a 5-pixel bottom-border using the primary color you defined above. You can easily reuse that variable like so:

border-bottom: 5px var(--color-primary) solid;

If at any time you want to change the site's color, you can simply change the variable definition in one place.

CSS variables also have scope. In order for the variables to be available across your site, you'll want to include them in the highest level element: root.

:root {
    --color-primary: #4248f4;


You can now use  var(--color-primary) variable anywhere to refer to your site's main color.

CSS Variables also have excellent support in modern browsers as can be seen on caniuse.com.