CSS Custom Properties (Variables)

CSS Custom Properties, or otherwise known as CSS Variables, allow us to handle dynamic values in our CSS. In the past, we had to use CSS preprocessors like Sass and Less to handle dynamic values or variables in our CSS. Now, CSS Custom Properties give us a native option that doesn’t have to be compiled and we can even access the variables in our JavaScript. You’ll get used to the weird syntax!

The process of defining and using variables is pretty similar no matter what part of the DOM you’re referencing. We will start with the root element, the body.

Define a variable by adding the two lines in front of its name (--). To reference the variable, use var(--style)

:root {
   --main-bg-color: #f4f4f4;
}

body {
   background-color: var(--main-bg-color);
}

Defining style variables for a div follows pretty much the same format. When you have a lot of variables, it can be helpful to separate the styles and the variables into two sections both referencing the same element.

.box {
   --box-bg-color: #fff;
   --box-main-color: #0e7;
}

.box {
   background-color: var(--box-bg-color);
   color: var(--box-main-color);
}

If you don’t have that many variables, you can define and reference them within the same block.

.grid {
   --gap: 20;
   grid-gap: var(--gap);
}

We can get access to the style variables we defined in CSS in our JavaScript. In this example, I’m referencing the box div, compiling all of the div‘s applied styles into a variable called boxStyles and getting access to the --box-main-color CSS variable from the boxStyles array.

const box = document.querySelector('.box');
const boxStyles = getComputedStyles(box);
const boxMainColor = boxStyles.getPropertyValue('--box-main-color')

const header = document.querySelector("#main-header");
header.style.setProperty("--header-bg-color", boxMainColor);

I then set the header’s --header-bg-color CSS variable value to that of the boxMainColor that we extracted in the lines above.

One thought on “CSS Custom Properties (Variables)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s