A quick view at CSS Variables (Custom properties)

Posted on

For quite some time we had variables in CSS with the help of SASS/LESS. Variables are useful, but they come with a drawback - you cannot use them in runtime. Well that time has ended - CSS variables are landing in new browsers.

can i use table for css variables [screen taken - 2016-12-20, you can view up to date table here here]

Caniuse table shows that major browsers aside Edge already support

:root {
  --header-color: #06c;

#foo h1 {
  color: var(--header-color);

example taken from [0]

Variables have two dashes --my-var before them and you can choose a name for them of your liking. To use variables you will need to use var keyword as in var(--my-var)

Well you are probably thinking - damn that is one ugly syntax! Where is my $foo? Well CSSWG wanted to leave this notation for some cool feature in futurre. More about it here [3]


You probably noticed :root selector in the syntax example. It assigns our custom named property --header-color to root element with value of #06c. Our defined property will be inherited to the rest of document elements


Taken from Javascript30 challenge challenge - CSS Custom properties with sliders example.

Below you can see how moving a slider sets CSS property and CSS automatically reacts

Setting CSS property with Javascript

document.documentElement.style.setProperty(`--header-color`, `red`);

Working code example - github

More use cases

Separating strings in internationalisation

:root:lang(en) {--external-link: "external link";}
:root:lang(de) {--external-link: "externer Link";}

a[href^="http"]::after {content: " (" var(--external-link) ")"}

taken from [2]


calc function can also be tied neatly

--one: calc(var(--two) + 20px);

Custom properties are quite cool - although we cannot throw SASS/Less in favour of them because lack of support of other features - mixins, nesting. Browser support is also still behind. All in all, still an interesting thing to try out. I bet in year or two we will be using them daily


If you have any suggestions - I am eagerly waiting for feedback. https://benetis.me/old/posts/contact-me/