How I Utilized CSS Variables in My Portfolio Site

Variables in CSS

Before we dive in, let's get a little more info on why variables in CSS are helpful. Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring a global search and replace if that color needs to change. CSS variables allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, is easier to understand than , especially if this same color is also used in other contexts.


Declaring a custom property is done using a custom property name that begins with a double hyphen (), and a property value that can be any valid CSS value. Like any other property, the selector given to the ruleset defines the scope that the custom property can be used in. The best practice is to define custom properties on the pseudo-class, so that it can be applied globally across your project. Here's what our default CSS looks like:

This gives us:

Implementation for Different Themes

Here’s the cool part! Now that we have established our let’s see how we can implement different CSS values all at the click of a button.

This is the code used to create the wrapper we’re affecting when we change the theme. Notice the function. You can use the custom property value by specifying your custom property name inside the function, in place of a regular property value.

So all that’s left to do is add a little JavaScript to get the user input. There are a couple of different ways to accomplish this, but the easiest way I found was using some conditional logic.

You’ll have to create a couple of different CSS files using the same structure we used for our default page and set up some on-click functionality, but other than that you’re all set. If you run into any snags along the way I’d be happy to help! You can reach out to me on LinkedIn or my portfolio site. Both of which I linked below. Happy coding!