Using CSS Variables

Using CSS Variables
udemy2 placeholder image

By now, most people know what a CSS preprocessor is and why they are so popular. If not, CSS preprocessors like Stylus work by taking CSS-like markup and converting it to the pure CSS that browsers understand and parse. A major feature common to all CSS preprocessors is the ability to create a variable and use it anywhere you want.

In other words, instead of doing something like this:

	
    .thing {
        color: #360a4a;
    }

    .other-thing {
        color: #360a4a;
    }
	

You can do this in Stylus:

	
    $sabe-purple: #360a4a;

    .thing {
        color: $sabe-purple;
    }

    .other-thing {
        color: $sabe-purple;
    }
	

Great, so if I can do the same thing with a CSS preprocessor, who cares about CSS variables, right? Well, not only do CSS variables offer more functionality, but they're also native, meaning you don't need a CSS preprocessor to do the job.

Let's look at the above example with CSS variables:

	
    :root {
        --sabe-purple: #360a4a;
    }

    .thing {
        color: var(--sabe-purple);
    }

    .other-thing {
        color: var(--sabe-purple);
    }
	

The end result is the same but the difference is that color is still being set to a variable and not a raw color value, like with the output of Stylus files. This means that you can still modify that variable and let the browser do the work of updating everything else.

Using CSS Variables with JavaScript

Because CSS variables are still variables, we can use JavaScript. to modify their values whenever we want. If you wanted to change the color of .thing and .other-thing, you would need to target both elements and then apply the style changes. With CSS variables, it is as simple as changing the value of that variable.

	
    document.documentElement.style.setProperty("--sabe-purple", "#472856");
	

And just like that, we changed the value of --sabe-purple from #360a4a to #472856.

Getting the current value of a CSS variable is also just as simple:

	
    var value = document.documentElement.style.getPropertyValue("--sabe-purple");
    console.log(value);
	
	
    #472856
	

Being able to dynamically set and get a CSS variable is an immensely powerful feature because it means that you are no longer held down by one of the biggest downsides of CSS preprocessors; the output in pure CSS is static and cannot be changed without hacking the DOM and manually applying styles all over the place.

If you use a CSS preprocessor variable in 50 different places, you must now change the styles in 50 different places, or be forced to use a class to override them all. Now with CSS variables, you just change the variable's value using a single line of code.

This means that with CSS variables, you now have dynamic styling; styling that isn't static and can change on a fly.

Below is a fully-working example of a pretty simple application of CSS variables. Click on the screen to change the background color to a random color:

	
    <!DOCTYPE html>
	<html>
		<head>
			<title>CSS Variables</title>
			<style>
				:root {
					--color: lightblue;
				}
				body {
					background-color: var(--color);
				}
			</style>
		</head>
		<body>
        </body>
		<script>
            var setDocumentVariable = (propertyName, value) => {
                document.documentElement.style.setProperty(propertyName, value);
            }

            document.addEventListener('click', (event) => {
                setDocumentVariable('--color', '#' + ((1 << 24) * Math.random() | 0).toString(16));
            });
		</script>
	</html>
	

CSS variables are pretty fun to play around with and create new experiences with. Definitely keep an eye open for them because they could very well go on to dominate as browser support for them continues to improve.