Here we are discussing the new feature in CSS3, Variables!

Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change.

CSS variables are set using custom property notation (e.g. --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);) .

Note: This feature is not supported in Internet Explorer!

The following example first defines a global custom property named “- -bg-color”, then it uses the var() function to insert the value of the custom property later in the style sheet:

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

Using var() you can define multiple fallback values when the given variable is not yet defined;

#div1 {
background-color: var( --bg-color,red); /* Red if --bg-color is not defined */
}
#div2 {
background-color: var(--bg-color,blue);/* Blue if --bg-color is not defined */
}

To use the values of custom properties in JavaScript, try like

// get variable from inline style
element.style.getPropertyValue("--bg-color");

// get variable from wherever
getComputedStyle(element).getPropertyValue("--bg-color");

// set variable on inline style
element.style.setProperty("--bg-color", "green");

Custom properties do inherit. Which means that if no value is set for a custom property on a given element, the value of its parent is used.

Happy Reading!

A <>er

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store