CSS: How to define and use variables

CSS has a mechanism that allows you to set up custom properties and then use them in CSS definitions as if they are variables. For example:

/* CSS Variables */
:root {
  --primary: #fff;
  --dark: #333;
  --light: #fff;
  --shadow: 0 1px 5px rgba(104, 104, 104, 0.8);

When defining CSS variables, there are two syntactical things to note:

  1. You must declare the scope of the variable. In the above example it was defined as :root, which signifies that the variable can be used anywhere in the CSS.
  2. Variable names begin with double dashes and are case sensitive. For example: --light

To use the value of the newly defined variable in some other property, the syntax CSS requires is to use the var() function, where the name of the variable is placed in the parenthesis. For example:

.btn {
  background: var(--dark);
  color: var(--light);

For more information about CSS variables and use of the var( ) function, see: