Dofactory.com
Dofactory.com
Earn income with your CSS skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

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.

Example

#

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

A fixed-width element
<style>
  :root {
    --width: 300px;
  }

  .variables {
    width: var(--width);
    border: 3px solid lightblue;
    padding: 25px;
  }
</style>

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

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
<style>
  :root {
    --main-bg-color: aliceblue;
    --main-txt-color: navy;
  }

  .var {
    background-color: var(--main-bg-color);
    color: var(--main-txt-color);
    padding: 15px;
  }
</style>

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

Browser support

This table shows when var support started for each browser.

Chrome
49.0 Sep 2016
Firefox
31.0 Jun 2014
IE/Edge
15.0 Apr 2017
Opera
36.0 Mar 2016
Safari
9.1 Mar 2016

You may also like


Last updated on Sep 30, 2023

Earn income with your CSS skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

Guides