CSS Variables

I’ve used variables in SASS and LESS before, but I always prefer the native approach.

Today I learned the basics of CSS Custom Properties, also known as Variables.


  • Like other variables, CSS Custom Properties lives in the scope they were declared in

  • Variables are inherited. Therefore, defining a var on the :root class will make it global (<html> tag).

  • CSS Variables have access to the DOM, unlike SASS and LESS. This means you can leverage things like screen size to update your variables.

CSS by Peter Griffin


  • Declaration: the property should start with two dashes

    .example {
      --example-color: #ffff66;
  • Access: use the var() function, and pass in the name of the variable as the parameter

    #title {
      color: var(--example-color);
  • Access vars with JavaScript

const example = document.getElementsByClassName('example');
const exampleStyles = getComputedStyle(example);
-> #ffff66

example.style.setProperty('--example-color', '#3399ff')

Browser compatibility

browser compatibility table taken from MDN web docs

comments powered by Disqus