Member-only story
CSS Custom Properties
2 min readMay 17, 2022
Also Called CSS Variables
CSS Custom Properties are commonly referred to as CSS Variables. We’ll use the term CSS variables for this article.
Why use CSS variables?
- They help not repeating yourself, DRY code. The code may be easier to maintain as code may be set in one place and used in many places.
- They are very helpful in creating color themes. Set in one place and used throughout.
- Perhaps most importantly they can be changed with JavaScript.
What values may be set using variables? Virtually any common CSS rule can have the values set using variables.
::root {--spacing: 1rem;}div {
padding: var(--spacing);
margin: var(--spacing);
}
Setting CSS variables:
html {
--color-black: #FFF;
--color-white: #000;
}
or
::root {
--color-black: #FFF;
--color-white: #000;
}
These two declarations are about the same, however, the ::root declaration has more specificity than the html. If the rules are declared in both the ::root declaration will have precedence.