CSS var() function

Definition and usage

CSS var() Function used to insert the value of CSS variables.

Instance

Example 1

First, declare a global variable named --main-bg-color, and then use it in the stylesheet. var() Function to insert the value of the variable:

:root {
  --main-bg-color: coral;
}
#div1 {
  background-color: var(--main-bg-color);
}
#div2 {
  background-color: var(--main-bg-color);
}

Try it yourself

Example 2

Another use var() Example of inserting multiple CSS variable values with the function:

:root {
  --main-bg-color: coral;
  --main-txt-color: blue;
  --main-padding: 15px;
}
#div1 {
  background-color: var(--main-bg-color);
  color: var(--main-txt-color);
  padding: var(--main-padding);
}
#div2 {
  background-color: var(--main-bg-color);
  color: var(--main-txt-color);
  padding: var(--main-padding);
}

Try it yourself

CSS syntax

var(--name, value)
Value Description
--name Required. Variable name (must start with two hyphens).
value Optional. Alternate value (to be used if the variable is not found).

Technical details

Version: CSS3

Browser support

The numbers in the table represent the first browser version to fully support this function.

Chrome Edge Firefox Safari Opera
49 15 31 9.1 36

Pagine correlate

Tutorial:Variabili CSS