DEV Community

Cover image for JavaScript30: Day 3 - CSS Variables😲😲🙀
Anik Khan
Anik Khan

Posted on

JavaScript30: Day 3 - CSS Variables😲😲🙀

I've created a project based off of the JavaScript30 Challenge by Wes Bos.
It was about using CSS variables!! I am not sure about you, but I was quite surprised when Wes Bos said that CSS has variables!! I couldn't just wait to try it out.

What So Special About CSS variables?

CSS variables are not like SASS variables. You can change the CSS variables value from HTML via JavaScript DOM manipulation. How cool is that!💗

What the project about?

It is to create some input control for blur effect, padding, and changing the background on an image.


  • My main lesson was to try the CSS variables and changing their values using DOM manipulation.
  • CSS variables should be declared at the root with --
/*these are the css variables*/
:root {
    --space: 10px;
    --blur: 0px;
    --color: #fa8072;
Enter fullscreen mode Exit fullscreen mode
  • We assign them like-
img {
    background: var(--color);
    padding: var(--space);
    filter: blur(var(--blur));
Enter fullscreen mode Exit fullscreen mode
  • Also got a chance to know more about the template string. I was stuck for a while because of this-
 //create property and set value accordingly`${}`, this.value + unit);

//`${}` is so wrong. I thought it would give me output like: --space
//correct way: `--${}`
Enter fullscreen mode Exit fullscreen mode

Live URL

There you go:

Alt Text


Here's the Js code, plz refer to GitHub for full code-

//changeTheImage method
const changeTheImage = function () {
    //get the unit
    const unit = this.dataset.sizing || ``;

    //create property and set value accordingly`--${}`, this.value + unit);

    /********PERSONAL EXPERIMENT*********/
    //console.log(`--${}`) //this is correct
    //console.log(typeof `--${}`) //string
    //console.log(typeof this.value) //string
    // console.log( //this is wrong
    // console.log(--`${}`) //this is wrong

//select all the inputs
const inputs = document.querySelectorAll('input');

//addEventlistener to each of the input to detect change
inputs.forEach((input) => input.addEventListener('change', changeTheImage));
inputs.forEach((input) => input.addEventListener('mousemove', changeTheImage));
Enter fullscreen mode Exit fullscreen mode


View on GitHub

Top comments (2)

richytong profile image
Richard Tong

Thanks for this article. I didn't have any idea there were variables in CSS too. Looks like they've been out and are well documented

akdeberg profile image
Anik Khan

Yeah, it caught me surprise that I didn't know about such a nice thing. And special thanks for the documentation links. It'll be mine go-to resource😉