Andrew's Digital Garden

CSS Custom Properties

Officially 'CSS Custom Properties', but commonly referred to as CSS variables.

These allow you to store runtime values in variables, and re-use them throughout your styles. This can help promote re-use, and keep your code [[20200307105301-dry]].

Note that custom properties are subject to the cascade and inherit their value from their parent. That is, they can be used at the level they are set and below. If a variable has a different value set, that will be overwrite the existing value only for it and it's descendants. [[20231215081938-css-variables-flow]]

To aid with this, 'global variables' are often places in the :root selector.

Values are then read using the var selector.

:root { --main-bg-color: brown; } div { background-color: var(--main-bg-color); }

Fallback values can also be used, if the CSS variable is not present. More that one fallback can be used.

div { background-color: var(--main-bg-color, red); color: var(--theme-color, var(--fallback-color, pink)) }

When the browser encounters an invalid var substitution, then the initial or inherited value of the property is used. This is in contrast to when var is not used, in which case earlier valid rules do apply. Somewhat related: [[20230728020610-grouping-selectors-browser-execution]]

getPropertyValue can be used to retrieve the value of a CSS variable in [[js]]:

getComputedStyle(element).getPropertyValue("--my-var");

https://dev.to/afif/what-no-one-told-you-about-css-variables-553o

[[20231031024400-cyclic-css-variables]]

[[css]]

CSS Custom Properties