Member-only story

CSS Custom Properties

Rich Brown
2 min readMay 17, 2022

--

Also Called CSS Variables

Picture by Author

CSS Custom Properties are commonly referred to as CSS Variables. We’ll use the term CSS variables for this article.

Why use CSS variables?

  1. 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.
  2. They are very helpful in creating color themes. Set in one place and used throughout.
  3. 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.

--

--

Rich Brown
Rich Brown

Written by Rich Brown

Passionate about using AI to enhance daily living, boost productivity, and unleash creativity. Contact: richbrowndigital@gmail.com

No responses yet