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,
--main-text-color is easier to understand than
#00ff00, 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
:root 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
:root 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
var() function. You can use the custom property value by specifying your custom property name inside the function, in place of a regular property value.
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!
Having recently completed the intensive Software Engineering program at Flatiron, I am ready to implement and maintain…