css change variable code example
Example 1: css set variable
:root {
--main-bg-color: coral;
}
#div1 {
background-color: var(--main-bg-color);
}
#div2 {
background-color: var(--main-bg-color);
}
Example 2: create variable in css
:root {
--tab-count: 5;
}
#div1 {
width: calc(100% - var(--tab-count));
}
Example 3: css variables
:root {
--background-color: #333;
--text-color: #fff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
Example 4: 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 5: css variable
...
<style>
:root{
--couleur-principale: brown;
}
#test1{
color:var(--couleur-principale);
}
</style>
...