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, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.

Utilization

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.

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!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Best Book of Python for beginners ?

Unit Tests are NOT for finding bugs

How to Improve Release Day Testing For an eCommerce Website

rubix cube floating with other cubes

Provision Highly Available VPC Architecture using CloudFormation | Fit-DevOps

🙋🏻🙋🏻‍♂️ Microservices Quiz Day

Fundamental of MongoDB using Python

4 Things I Should’ve Done While Getting My STEM Degree

Dive into GraphQL

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcus Siegel

Marcus Siegel

More from Medium

— — My First Flight

The story of Pixel Lobsters…

New Smyrna