At first when I heard of css variables when it was introduced, I was a bit skeptical. Why would anyone use it if there are extension languages as scss, sass, less and stylus. After several years, I started to notice more and more peoples using it, writing about it and talking about it. I was missing out on something... It took a while but after using it here and there, I was hooked. In this post I'll cover what convinced me to explore css variables further and to start using them in projects.
To declare variables, define them in a selector and prefix the variable names with two dashes (
A popular approach is to define variables with the
:root selector, this way you're defining a global variable:
To use the variables, use the
var() function accepts a second parameter, which is used as a fallback if the variable has not been declared:
The snippets above results in:
With css variables, creating a theme becomes simple.
Depending on the
body's class we can set the variable to its appropriate value:
We can then use these variables when we style elements:
body's class changes to
sunset, the css variables will cascade to all of the selectors.
In our case, we'll transition to a light or dark theme:
To get a variable, use the
To get a value from an element, first select that element with
To set a variable value, use
To set a value on an element:
This API opens up some opportunities to use css variables in a clean way.
I encountered this use case a couple of days ago by David K. in one of his XState demos at https://codepen.io/davidkpiano/pen/zWrRye. He uses css variables to create a selection box when the user drags the mouse across the screen.
The css of the selectbox uses the variables to know the four corners (based on the starting point and the current position of the mouse) of the box:
Listen on the mouse events, and update the the mouse points accordingly:
Ending word link
Feel free to update this blog post on GitHub, thanks in advance!
I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.