CSS Variables Explained in 2 Minutes with an Interactive Demo

  • Gabriel Romualdo

  • January 27, 2020

Go check out Daily Developer Jokes, my latest project!

Daily Developer Jokes Website Follow Daily Developer Jokes on DEV

Here's the joke from today:

Daily Developer Jokes, Friday Jan. 27, 2020


CSS variables have been around for quite some time now, but are nevertheless extremely useful.

They can be defined in an element like this:

element {
    --my-variable: #555;
}

The value of a variable can be just about anything, from pixel values to colors to linear-gradients.

You can use a variable almost anywhere by wrapping it in a var function:

another-element {
    color: var(--my-variable);
}

Why Not Use a Preprocessor for Variables?

This is a very common question, as preprocessors seem to have solved the CSS variable problem even before native CSS variables existed!

However, CSS variables can be changed in real-time and aren't compiled, which means that it is possible to change the value of a CSS variable within JavaScript, and all references to that variable will be automatically changed. The example coming up uses this ability pretty well, and uses this ability of CSS variables to its advantage.

A Demo of CSS Variables in Action

One use CSS variables is the ability to use a singular variable for a site's primary color, and then allow the user to interactively change that primary color as they wish.

Here's a fun little CodePen that shows just that!

See the Pen CSS Variables Demo by Gabriel Romualdo (@xtrp) on CodePen.

Here, I use some basic JavaScript code to change the CSS variable, and thus changing the theme color of the entire page.

Other Use Cases of CSS Variables

The example above is one of the many example use cases of CSS variables. Other possible uses include:

  • Creating a CSS variable for a default font size of an element and dynamically changing that for disabled users
  • Creating a CSS variable for the height and width of an element and dynamically changing that variable in a CSS animation
  • Creating CSS variables for each of the colors on your site an dynamically changing those variables to create a "dark mode" or different theme

Browser Support & Conclusion

CSS variables are supported in all major browsers except IE, QQ, and Baidu: CanIUse Data for CSS Variables.

I hope you enjoyed this explanation and demo of CSS variables and find them to be useful in your sites. I personally use CSS variables for colors and font sizes on the several of my sites, and have found them to help keep my styles much cleaner and easier to read and refactor.

Thanks for scrolling.

— Gabriel Romualdo, January 27, 2020