Happy holiday folks! All the best from us at Digitpaint
👑

Day 1

Varying variables with CSS

The era of needing css pre-processors to use variables is over! (for everyone that is not still using IE, that is…) This new school of css custom properties can, in fact, do even more than the likes of SASS are even capable of!

Let's start with a little show-and-tell about how to use these variables in a few ways. Change the colors of the ornaments in the christmas tree below!

So how does this work?

Pretty neat, huh? Let's dig deeper! We'll start at the beginning; how do you declare these variables? You set a value onto one of these variables by just using regular ol' CSS syntax. If you want to use one of these as a global variable, set it up inside :root. It will look something like this:

:root {
  --ballColor: #f00;
}

.ball {
 background: var(--ballColor);
 color: var(--ballTextColor, #000);
}

// Set this on a wrapping element
.digitpaint-theme {
  --ballColor: #5f276d;
} 

As you can see, we use --variable to define a variable and we use them by using the CSS var() function.

The really nice thing is that variables can be used and overriden. Even in media queries, which pre-processors can't even do. var(), however, is more versatile than that. You can also use it to set defaults, which we have done in the example above with the --ballTextColor variable. These defaults can also make use of another var(). This will look like the following snippet:

.someOtherDiv {
  padding: var(--someVariable, var(--someOtherVariable, 15px));
}

Note that the backup in the sample above is --someOtherVariable. When this variable isn't set either, the padding will be set to 15px.

Enter JavaScript

You can change the value of variables using JavaScript with the following syntax:

// A global variable on :root
document.documentElement.style.setProperty(--ballColor, "#00f");

// A variable set on a specific element
document.querySelector(.ball).style.setProperty(--ballColor, "#00f"); 

This is exactly what we do with the sled in the demo above. We have added an eventlistener to the mousemovement in JavaScript and we assign the mouse coordinates to two variables which in turn we use in the CSS to place the sled.

Browser compatibility

So what about browser support for CSS Variables? That's pretty decent actually, only IE is missing out.

  • Chrome
  • Edge
  • FireFox
  • Samsung Internet
  • Chrome for Android
  • Safari
  • iOS Safari
  • opera

More detailed information on caniuse.com

Learn more

Demo source code

Do you want to dig in the nitty-gritty of this demo, check out the source files:

Back to home