css custom properties code example
Example 1: css custom properties
:root {
--variable-name: variable-property;
}
selector {
property: var(--variable-name);
}
Example 2: css variable
:root {
--main-bg-color: pink;
}
body {
background-color: var(--main-bg-color);
}
Example 3: javascript use css custom properties
Values in JavaScript
To use the values of custom properties in JavaScript, it is just like standard properties.
element.style.getPropertyValue("--my-var");
getComputedStyle(element).getPropertyValue("--my-var");
element.style.setProperty("--my-var", jsVar + 4);
Example 4: custom properties css
element.style.getPropertyValue("--my-var");
getComputedStyle(element).getPropertyValue("--my-var");
element.style.setProperty("--my-var", jsVar + 4);