Coming Soon: Native CSS Variables

Craig Buckler
Share

Name one feature you’d love to see in CSS. Hands up those who want variables… (I’m sure some of you are desperate for parent selectors but you’re in the minority!)

The issue stems from our need to use and repeatedly re-use the same colors and other values throughout a stylesheet. For example:


section { border-color: #334; }
h1      { color: #334; }
p       { background-color: #334; }

Maintenance is tougher than it need be. We need to remember a range of hex/RGB values and, inevitably, the finicky client or designer will decide #335 is “on-brand”. Search and replace might work, but not if you’ve used #333344 in some places or rgb(21,21,2c) in others.

CSS variables solve the problem. You define #334 as a single named variable and use it throughout your code. It’s usually the first feature implemented in CSS pre-compilers. For example, in LESS:


@mycolor: #334;
section { border-color: @mycolor; }
h1      { color: @mycolor; }
p       { background-color: @mycolor; }

or Sass


$mycolor: #334;
section { border-color: $mycolor; }
h1      { color: $mycolor; }
p       { background-color: $mycolor; }

Fortunately, native CSS variables will arrive soon. There’s a draft W3C specification at https://www.w3.org/TR/css-variables/ which reveals how we may be writing CSS code when vendors begin to implement support.

According to the document, any property name starting with the ‘var-‘ prefix is a variable property. For example:


:root
{
  var-mycolor: #334;
}
section { border-color: var(mycolor); }
h1      { color: var(mycolor); }
p       { background-color: var(mycolor); }

Perhaps that’s not as concise as LESS/Sass, but it’s a big step forward which will ease the maintenance issues we’ve all encountered.

It’s an exciting development but don’t hold your breath. There’s no guarantee it will be adopted by all vendors and, even if they do, the feature does not appear to be backward-compatible with older browsers. Our great grand-children will love it, though.