CSS Variables

Enhance your CSS with variables without LESS or SASS

Sources

Medium article by Per Harald Borgen

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

1
2
3
4
5
6
:root {
  --brand-color: blue;
}
button {
  background-color: var(--brand-color);
}

Local

1
2
3
4
5
6
7
.alert {
  --alert-color: #ff6f69;
}
.alert p {
  color: var(--alert-color);
  border: 1px solid var(--alert-color);
}

Better responsiveness

1
2
3
4
5
6
7
8
:root {
  --main-font-size: 16px;
}
media all and (max-width: 600px) {
  :root {
    --main-font-size: 12px;
  }
}

How to access variables with JavaScript

1
2
3
4
5
var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var mainColor = rootStyles.getPropertyValue('--main-color');

root.style.setProperty('--main-color', '#88d8b0');
License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy