Introduction to CSS Variables

Spread the love

CSS Variables lets you use variables in your CSS rules, which results in less repetition, more flexibility and easier theming of your site. Unlike SASS and LESS, CSS Variables are part of the DOM, so you can use them directly in the browser.

Recent versions of most browsers support CSS Variables, IE does not support it, you can find the list of browsers supporting it here. There is a ploy-fill available here.

Declare variable

you declare variable names with “–” prefix

Syntax: --variable_name : value;
Example: --red: #FF0000;

Use variable

To use previously defined variables in css rules, you need to wrap the variable name in  “var()”

Example: color: var(--red);

Scope

CSS variables have 2 scopes, 

Global Scope

Variables declared with global scope can be used in any elements, you can declare variables with global scope in a :root selector or the html selector

:root {
--red: #FF0000;
}

html {
--red: #FF0000;
}

Local Scope

Variables declared with local scope can be used in the children of that element.

div {
--red: #FF0000;
}

div p {
color: val(--red);
}

Get and Set Values with Javascript

If you want to get the value of a css variable through javascript, you can do so with the following syntax


getComputedStyle(element).getPropertyValue('--variable_name') 

where element is the DOM element that has the creation of the css variable. To access the :root element/selector in JavaScript, use document.documentElement.

To set the value of a css variable through javascript, use the setProperty method as shown below

element.style.setProperty('--variable_name', 'value')