Menü schliessen
Created: August 18th 2021
Last updated: December 10th 2021
Categories: Common Web Development
Author: Tim Fürer

CSS: How to Use var()

Tags:  CSS,  HTML,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

var() is a CSS function that returns variables' values. Its functionality is limited to defining property values and var() may not be used for anything other than that. Using this function can make your CSS much quicker and easier to manage.

Defining a Variable

Basically, variables are properties. They, too, are defined inside rules, just like other properties. This comes with the handy effect that variables are only effective within the elements they're assigned to and any of those elements' children. The range in which a variable is effective is called its "scope".

Unlike normal properties, a variable's name must always begin with a double hyphen (- -). Other than that, the name can be freely chosen.

Example:

--example-variable: value;

To create a variable with a global scope, define it within the :root pseudo-class. This pseudo-class essentially mirrors the effect of adding "html" to your selector.

Example:

:root
{
	--example-variable: value;
}

Returning a Variable's Value

Simply insert a variable's name into the var() function and that variable's value will be returned.

Example:

property: var(--example-variable);

Changing a Variable's Value On the Fly With JavaScript

This is possible thanks to variables working like properties. It can be helpful for making things such as theme switchers. Target an element you have assigned a variable to and change the value similar to how you would with a property.

Example (targets :root):

document.documentElement.style.setProperty('--example-variable', 'value');

Additional Information