CSS Variables

Jeremie LitzlerLess than 1 minuteWeb FundamentalsWeb developmentCSSCSS Variables

Sources

Medium article by Per Harald Borgenopen in new window

Why learn CSS Variables?

  • To build a theme where you will reuse a property value many many many times
    • ex: the brand color or the size of a button.
  • To build better responsive designs

Local vs Global

Global

:root {
  --brand-color: blue;
}
button {
  background-color: var(--brand-color);
}

Local

.alert {
  --alert-color: #ff6f69;
}
.alert p {
  color: var(--alert-color);
  border: 1px solid var(--alert-color);
}

Better responsiveness

:root {
  --main-font-size: 16px;
}
media all and (max-width: 600px) {
  :root {
    --main-font-size: 12px;
  }
}

How to access variables with JavaScript

var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var mainColor = rootStyles.getPropertyValue('--main-color');

root.style.setProperty('--main-color', '#88d8b0');