Basics of CSS Variables

You can easily spot a CSS variable. It is any property that begins with two dashes.

Copy
--my-css-variable: green;

A CSS variable is sometimes called a “custom variable” because you can use whatever name you want (but don’t use spaces), rather than always adhering to standard CSS property names such as “color,” “width,” and “font-size.” For example, you might have a CSS variable written like this in order to identify a product color at your company.

Copy
--my-product-color: #bed420;

When a CSS variable is referenced by another property, it is done so with the var() function.

Copy
color: var(--my-product-color);

You can define a CSS variable either locally or globally. A locally defined CSS variable is set on a particular selector.

Copy
.banner-text
{
    --my-product-color: #bed420;
}

On the other hand, a globally defined CSS variable is set on the :root selector.

Copy
:root
{
    --my-product-color: #bed420;
}

When using the regular stylesheet, you can use the :root selector for your CSS variables.

Note Using the regular stylesheet is one place to manage CSS variables. If you are using CSS variables for branding, it is a good idea to use the branding stylesheet (i.e., the Branding.css file) to group all of your CSS variables in one place. When using the regular stylesheet (or a skin), you will have access to those variables to insert them as property values for different selectors. See Branding and CSS Variables.

Following are some other important considerations of CSS variables:

  • Normal rules of inheritance and cascading apply to CSS variables. See Inheritance and Cascading.
  • They are case-sensitive, so make sure you are consistent when creating and using them.
  • You can change the value under @media sections in order to override the value on the default medium. See Mediums and Media Queries.

    Example You might have the following set in the default medium.

    Copy
    :root
    {
        --my-product-color: #bed420;
    }

    But then you have this under the @tablet media query.

    Copy
    @media tablet
    {
        :root
        {
            --my-product-color: #1c5a97;
        }
    }

    As expected, the color will change from green to blue once the screen size is reduced to a tablet.

Note For more detailed information about CSS variables, you can refer to numerous third-party websites on the internet.