CSS Variables

CSS Variables

We all know that we’ve had variables in SASS/LESS etc for a long time. But did you know, that we have native CSS variables right in the browser now!? With zero compiling, transforms or transpiling.

CSS variables, like variables in any programming language, allow us to define styles and reference them anywhere else and even modify them with javascript.

CSS Variables are supported by all modern browsers, except IE
MDN is calling them Custom properties (–*)


How to use them

We can define any CSS property in a CSS variable, ie: color, border, size, position. We prefix their name with --. We declare them by adding them to any element, which will scope just like any other CSS property would.


:root {
  --base-color: #ffc600;
  --spacing: 10px;
  --blur: 10px;
} 

Remember, we can place these on any element, to create scoping. If we created these properties inside the class .main-content and tried to use them outside the scope of elements inside of that class, it would not be applied.


We use them by putting them inside of a var().


img {
  padding: var(--spacing);
  background: var(--base-color);
  filter: blur(var(--blur));
}

We can also provide an optional default value to the var() call.


padding: var(--spacing, 5px);

/* or even multiple fallbacks */
color: var(--color-one, --color-two, red);

You can access and modify your CSS variables in Javascript

One of the most powerful gains we get by using native CSS variables, is we can modify them right inside our page with javascript. Your transpiled languages like SASS are only for build time, and once they are set, they are set.


document.documentElement.style.setProperty('--base-color', 'blue');

No more adding-removing classes just to change between different style sets.


No more defining multiple variables for different media queries

…Or any other scoped changes.

So, you want different link styles on your mobile site than you do on your desktop site? And you still want to provide consistency with variables? Easy. We will use native CSS scoping to redefine the value of our variables only for that scope.


body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}

Working example

@Wesbos has a great example of this in his FREE #Javascript30 series. I’ve posted it in a codepen here for you to play with

Working Example


Reminder, Pluralsight has many courses on all of this in many different languages and implementations, and they have a FREE Trial!

Start a 10-day free trial at Pluralsight