CSS Variables

The var function inserts variable values into a stylesheet.

These variables are declared and assigned in a :root selector.

The root represents the root of the stylesheet.



The width of this element is assigned with a var function.

A fixed-width element
  :root {
    --width: 300px;

  .variables {
    width: var(--width);
    border: 3px solid lightblue;
    padding: 25px;

<div class="variables">
  A fixed-width element

Using CSS variables

CSS variables allows you to add custom property values.

The var() function is used to create CSS variables.

CSS variables are useful if you want to use custom values repeatedly by storing the property value inside the :root selector.

The var() function

CSS variables must be declared within the same CSS styling that defines its scope.

For global scope, the :root or body selector can be used.

Variable name must always begin with two dashes (--) and case sensitive.

The code below is the syntax on how the var() function is used.

var(custom-name, value)

The custom-name is the property's name (e.g. color, background).
The value is an optional fallback that will be used if the custom property is invalid.

Variables storing the background and text color values.

The Van Gogh exhibit is opening next week
  :root {
    --main-bg-color: aliceblue;
    --main-txt-color: navy;

  .var {
    background-color: var(--main-bg-color);
    color: var(--main-txt-color);
    padding: 15px;

<div class="var">
  The Van Gogh exhibit is opening next week

Browser support

This table shows when var support started for each browser.

49.0 Sep 2016
31.0 Jun 2014
15.0 Apr 2017
36.0 Mar 2016
9.1 Mar 2016

You may also like