The brave new world of CSS variables (Custom Properties)

I tend to avoid preprocessors or transpilers when it comes to coding for the front end. Something about them just don't feel right. But when it comes to managing CSS, I too get annoyed to write the same CSS value over and over again. It hurts my DRY feelings. That's why I prefer LESS over SASS in those situation. Something about LESS feels more familiar with normal CSS to me. That's a topic for another discussion.

Today I came across a CSS specification called CSS Custom properties. Like any other Cool CSS properties I meet along the way, I always open caniuse.com to look up it's browser compatibility. The result was good enough to convince me into writing this blog post. Click here to see for yourself

Defining a custom property:

A part of me really wished CSS variables to be declared the same way import, font-face or keframes were defined. But the folks at W3C had something different in mind. they envisioned something like this:

--some-custom-property:value;

This does add some extra benefit over global style variables thought, for starter, this variable(custom property) can be element specific, can be inherited or interestingly, local values can override inherited values, same as any other CSS property.

Using Custom properties:

Custom properties can be accessed with the old CSS function-line syntax. This time with var() syntax:

property: var(--some-custom-property);

In case a variable is not defined, you can also pass a default value as second parameter:

property: var(--some-custom-value,default-value);

Sample Code:

Some code is worth thousand words, that's why I provided sample code directly from CodePen.

See the Pen CSS Custom properties example by Anam Ahmed (@theanam) on CodePen.

The :root pseudo class might be another new thing to discuss here. using :root selector in CSS is almost like using the html selector in CSS. but :root has higher specificity that might come in handy in many awkward CSS situations.

Should I immediately start using it:

Maybe.... No. As of August 2018, custom property is a W3C candidate recommendation with a good browser support. Here's the W3C document. If you don't care about the user who did not update their browser since last one and half year and doesn't use opera mini, feel free to use custom properties in production and nobody will complain.

...Or you can use WebPack with postCSS, that has a plugin for CSS custom properties. or you can use a PolyFill.

Oh you can always use a fallback value like any other CSS values out there. But if you really need to use a fallback value, then what's the point of using variables in the first place?

I dream of a future when you will be able to use CSS custom properties without any preprocessor, transpiler, polyfill or anyone judging you.