Skip to main content

Quickstart to CSS Variables

Jul 21 '17

CSS variables are a new value available in most modern browsers. The only real exclusions are Opera Mini and IE11. They make your code more readable, cascade, and allow for greater control in theming.

Setting

:root {
 --grid-columns: 4;
 --grid-gap: 20px;
}

Getting

.grid {
  grid-template-columns: repeat(var(--grid-columns), 1fr);
  grid-column-gap: var(--grid-gap);
  grid-row-gap: var(--grid-gap);
  margin-top: var(--grid-gap);
}

Update with JS

// Select all inputs in grid-controls.
var controls = document.querySelectorAll('.grid-controls input');
// Save document root so we can update our variables.
var root = document.documentElement;
// Create a units variable so we can add `px` to units, if we need it.
var units;
 
function updateGrid() {
  if(this.id === 'grid-columns') {
  units = '';
  } else {
  units = 'px';
  }
 
  root.style.setProperty(`--${this.id}`, this.value + units);
}
 
// Update grid whenever an input is updated.
for(let control of controls) {
  control.addEventListener('change', updateGrid);
}

You need to refer to the root, because that's where your variables are set. To update the css variable you need to use style.setProperty(variableName, value [optional], important [optional]);

Use Cases

Like I mentioned before, CSS Variables could be great in re-theming something in different colors. For example, if you have a web app that requires different color schemes for different users. For updating values transform offset values for sticky headers. Creating demos like this CSS Grid intro.

See the Pen CSSGrid by James Mejia (@mejiaj) on CodePen.

Fun Fact

You can see how easy it is to create a repeated grid pattern with the new CSS Grid.

.grid {
  display: grid;
  grid-template-columns: repeat(var(--grid-columns), 1fr);
  grid-column-gap: var(--grid-gap);
  grid-row-gap: var(--grid-gap);
  margin-top: var(--grid-gap);
  align-items: stretch;
  // Transitions don't work yet.
  // transition: 0.3s ease-in-out;
}

Here we're basically saying: - I want a grid - Make it `X` amount of columns and each column should be 1 free space unit (basically divide it into this many columns) - Set the gutter

I'm outlining this because CSS Grid is getting better and better support. And this saves us from percentages and negative offsets. While also making the code more readable.

Read more about: