Do you know how powerful CSS variables are?
CSS variables are powerful, you may know that. You can use it for simple tasks, to easily store global variables like colors or fonts or enable dark mode on your website just by toggling a simple class on your body 🤯.
After years using CSS variables I’m still amazed by its power, and I want to show it to you, let’s get into coding some stuff with it.
Unfortunately, CSS lacked support for variables for a long time, so many used CSS preprocessors to have variables, but those ain’t real variables! You are just able to change them before compiling, not on runtime.
So lets dive in the power of runtime variables 🙌
What a classic! A wall clock 😅
What if I told you, this is the only JS you need:
I’ve used an HTML preprocessor, PUG, to quick build the HTML, note the usage of the index variable, it will be helpful in the next steps.
First stage is done, so easy, there’s not much to say here, just setting up the HTML and the hours/minutes/seconds variables, let’s move to CSS 🎯
This is where it gets fun, we start with hours/minutes/seconds as zero, I’m setting a size variable that uses the min CSS function, so the clock will always fit the screen, because it’s size is the minimum value between 24rem
, 75vh
75% of viewport height and 75vw
75% of viewport width.
Also, the font size is based on the size variable, this allows me to later use em sizes so the clock will always keep it’s proportions 👌
With a bit more css, we get the clock frame.
We now need to place the hour markers on the clock, let’s use --index
.
The main li
will have it’s origin on the center of the clock, and a rotation of a --rotation
variable, this way instead of always setting the transform on each child element, we just set the variable 🤷♂️
The clock has 12 sections, so 360 / 12 = 30 degrees, each marker will be positioned on index * 30deg
. And we’re done for the markers.
Now the pointers, we’ll use the same logic of having a main li
to handle the rotation variable. The hours will be multiplied by 30 degrees, 360 / 12 = 30, the minutes and seconds will be multiplied by 6 degrees, 360 / 60 = 6.
And we’re done, this is the main idea behind using CSS variables to create a wall clock, avoiding Javascript by delegating all the styles to the CSS.
The code is live on https://codepen.io/promatik/pen/gOLWzKK.
Have a look, and mess with the variables 🙌
This was my first article, let me know if you’re interested in more like this one, just leave some claps 👏 below and I’ll keep posting more stuff.